Skip to content

Commit

Permalink
Add logToFile, logToConsole flags for toggling logging.
Browse files Browse the repository at this point in the history
  • Loading branch information
jszuminski committed Jun 13, 2024
1 parent ced7b17 commit 8736ff8
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 33 deletions.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,9 @@ The format, along with its default values, is as follows (using the recommended
"logging": {
"level": 4,
"file": "highcharts-export-server.log",
"dest": "log/"
"dest": "log/",
"toFile": true,
"toConsole": true
},
"ui": {
"enable": false,
Expand Down Expand Up @@ -352,6 +354,8 @@ These variables are set in your environment and take precedence over options fro
- `LOGGING_LEVEL`: The logging level to be used. Can be **0** - silent, **1** - error, **2** - warning, **3** - notice, **4** - verbose or **5** benchmark (defaults to `4`).
- `LOGGING_FILE`: The name of a log file. The `logDest` option also needs to be set to enable file logging (defaults to `highcharts-export-server.log`).
- `LOGGING_DEST`: The path to store log files. This also enables file logging (defaults to `log/`).
- `LOGGING_TO_FILE`: Whether you want to enable or disable creation of the log directory and saving the log into a .log file (defaults to `true`).
- `LOGGING_TO_CONSOLE`: Whether you want to enable showing logs in the console or not (defaults to `true`).

### UI Config

Expand Down
3 changes: 3 additions & 0 deletions bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ See LICENSE file in root for details.

import main from '../lib/index.js';

import { initLoggerOptions } from '../lib/logger.js';
import ExportError from '../lib/errors/ExportError.js';

/**
Expand Down Expand Up @@ -47,6 +48,8 @@ const start = async () => {

// If all options correctly parsed
if (options) {
initLoggerOptions(options.logging);

// Print initial logo or text
main.printLogo(options.other.noLogo);

Expand Down
2 changes: 2 additions & 0 deletions lib/envs.js
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,8 @@ export const Config = z.object({
.transform((value) => (value !== '' ? parseFloat(value) : undefined)),
LOGGING_FILE: v.string(),
LOGGING_DEST: v.string(),
LOGGING_TO_CONSOLE: v.boolean(),
LOGGING_TO_FILE: v.boolean(),

// ui
UI_ENABLE: v.boolean(),
Expand Down
67 changes: 35 additions & 32 deletions lib/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,14 @@ See LICENSE file in root for details.

import { appendFile, existsSync, mkdirSync } from 'fs';

import { defaultConfig } from './schemas/config.js';

// The available colors
const colors = ['red', 'yellow', 'blue', 'gray', 'green'];

// The default logging config
let logging = {
// Flags for logging status
toConsole: true,
toFile: false,
toFile: true,
pathCreated: false,
// Log levels
levelsDesc: [
Expand Down Expand Up @@ -52,10 +50,13 @@ let logging = {
listeners: []
};

// Gather init logging options
for (const [key, option] of Object.entries(defaultConfig.logging)) {
logging[key] = option.value;
}
export const initLoggerOptions = (loggingOptions) => {
for (const [key, value] of Object.entries(loggingOptions)) {
logging[key] = value;
}

logging.toFile = false;
};

/**
* Logs the provided texts to a file, if file logging is enabled. It creates
Expand All @@ -66,28 +67,26 @@ for (const [key, option] of Object.entries(defaultConfig.logging)) {
* @param {string} prefix - An optional prefix to be added to each log entry.
*/
const logToFile = (texts, prefix) => {
if (logging.toFile) {
if (!logging.pathCreated) {
// Create if does not exist
!existsSync(logging.dest) && mkdirSync(logging.dest);
if (!logging.pathCreated) {
// Create if does not exist
!existsSync(logging.dest) && mkdirSync(logging.dest);

// We now assume the path is available, e.g. it's the responsibility
// of the user to create the path with the correct access rights.
logging.pathCreated = true;
}
// We now assume the path is available, e.g. it's the responsibility
// of the user to create the path with the correct access rights.
logging.pathCreated = true;
}

// Add the content to a file
appendFile(
`${logging.dest}${logging.file}`,
[prefix].concat(texts).join(' ') + '\n',
(error) => {
if (error) {
console.log(`[logger] Unable to write to log file: ${error}`);
logging.toFile = false;
}
// Add the content to a file
appendFile(
`${logging.dest}${logging.file}`,
[prefix].concat(texts).join(' ') + '\n',
(error) => {
if (error) {
console.log(`[logger] Unable to write to log file: ${error}`);
logging.toFile = false;
}
);
}
}
);
};

/**
Expand All @@ -102,7 +101,7 @@ export const log = (...args) => {
const [newLevel, ...texts] = args;

// Current logging options
const { level, levelsDesc } = logging;
const { levelsDesc, level } = logging;

// Check if log level is within a correct range or is a benchmark log
if (
Expand All @@ -124,15 +123,17 @@ export const log = (...args) => {
});

// Log to console
if (logging.toConsole) {
if (logging.toConsole)
console.log.apply(
undefined,
[prefix.toString()[logging.levelsDesc[newLevel - 1].color]].concat(texts)
);
}

// Log to file
logToFile(texts, prefix);
if (logging.toFile) {
console.log('log to file: ');
logToFile(texts, prefix);
}
};

/**
Expand Down Expand Up @@ -189,7 +190,9 @@ export const logWithStack = (newLevel, error, customMessage) => {
});

// Log to file
logToFile(texts, prefix);
if (logging.toFile) {
logToFile(texts, prefix);
}
};

/**
Expand Down Expand Up @@ -238,7 +241,7 @@ export const initLogging = (logging) => {
setLogLevel(logging && parseInt(logging.level));

// Set the log file path and name
if (logging && logging.dest) {
if (logging && logging.dest && logging.toFile) {
enableFileLogging(
logging.dest,
logging.file || 'highcharts-export-server.log'
Expand Down
14 changes: 14 additions & 0 deletions lib/schemas/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,20 @@ export const defaultConfig = {
cliName: 'logDest',
description:
'The path to store log files. This also enables file logging.'
},
toFile: {
value: true,
type: 'boolean',
envLink: 'LOGGING_TO_FILE',
cliName: 'logToFile',
description: 'Enables logging to a file.'
},
toConsole: {
value: true,
type: 'boolean',
envLink: 'LOGGING_TO_CONSOLE',
cliName: 'logToConsole',
description: 'Enables logging to the console.'
}
},
ui: {
Expand Down

0 comments on commit 8736ff8

Please sign in to comment.