Skip to content

Instantly share code, notes, and snippets.

@shinaisan
Created August 30, 2018 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shinaisan/27b399da851297c3956bf7ff80df7e83 to your computer and use it in GitHub Desktop.
Save shinaisan/27b399da851297c3956bf7ff80df7e83 to your computer and use it in GitHub Desktop.
Winston transports.File Example
const { createLogger, format, transports } = require('winston');
let test = {};
test.common = (pretty, args) => {
const output = (pretty
? format.prettyPrint()
: format.simple());
const logger = createLogger({
format: format.combine(
format.splat(),
format.timestamp(),
output
),
transports: [
new transports.File({
filename: './info.log',
level: 'info'
}),
new transports.File({
filename: './error.log',
level: 'error'
})
]
});
if ((!!args) && (args.length > 0)) {
logger.info('arguments: %o', args);
} else {
logger.error('Invalid arguments: %o', args);
}
};
test.simple = (args) => (test.common(false, args));
test.pretty = (args) => (test.common(true, args));
if (require.main === module) {
const name = process.argv[2];
const args = process.argv.slice(3);
if (!name) {
test.simple();
} else {
test[name](args);
}
}

info.log

{ level: 'error',
  message: 'Invalid arguments: [ [length]: 0 ]',
  timestamp: '2018-08-30T00:11:15.293Z',
  [Symbol(level)]: 'error',
  [Symbol(splat)]: [ [] ] }
{ '0': 'hello',
  level: 'info',
  message: 'arguments: [ \'hello\', [length]: 1 ]',
  timestamp: '2018-08-30T00:11:26.820Z',
  [Symbol(level)]: 'info',
  [Symbol(splat)]: [ [ 'hello' ] ] }
{ '0': 'hello',
  '1': 'world',
  level: 'info',
  message: 'arguments: [ \'hello\', \'world\', [length]: 2 ]',
  timestamp: '2018-08-30T00:11:36.403Z',
  [Symbol(level)]: 'info',
  [Symbol(splat)]: [ [ 'hello', 'world' ] ] }

error.log

{ level: 'error',
  message: 'Invalid arguments: [ [length]: 0 ]',
  timestamp: '2018-08-30T00:11:15.293Z',
  [Symbol(level)]: 'error',
  [Symbol(splat)]: [ [] ] }

info.log

info: arguments: [ 'hello', [length]: 1 ] {"0":"hello","timestamp":"2018-08-30T00:09:46.253Z"}
info: arguments: [ 'hello', 'world', [length]: 2 ] {"0":"hello","1":"world","timestamp":"2018-08-30T00:09:59.756Z"}

error.log

error: Invalid arguments: undefined {"timestamp":"2018-08-30T00:09:18.115Z"}
error: Invalid arguments: [ [length]: 0 ] {"timestamp":"2018-08-30T00:09:33.387Z"}
{
"name": "winston-transports-file-example",
"version": "1.0.0",
"description": "Winston transports.File Example",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "shinaisan@users.noreply.github.com",
"license": "ISC",
"dependencies": {
"winston": "^3.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment