10 examples of 'express winston' in JavaScript

Every line of 'express winston' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
21public set winston(winstonInstance: winston.LoggerInstance) {
22 this.winstonInstance = winstonInstance;
23}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

11function createLogger(level, name) {
12 // a singleton and default logger
13 const {
14 config
15 } = winston;
16 const logger = new winston.Logger({
17 level,
18 transports: [
19 new winston.transports.Console({
20 timestamp: () => new Date().toISOString(),
21 handleExceptions: true,
22 formatter: (options) => {
23 return `${options.timestamp()} ${
24 config.colorize(options.level, options.level.toUpperCase())} ${
25 name ? config.colorize(options.level, `[${name}]`) : ''
26 } ${options.message ? options.message : ''} ${
27 options.meta && Object.keys(options.meta).length ? `\n\t${JSON.stringify(options.meta)}` : ''}`;
28 }
29 })
30 ],
31 exitOnError: false
32 });
33 return logger;
34}
5export function logger(winstonInstance) {
6 winstonInstance.configure({
7 level: config.debugLogging ? 'debug' : 'info',
8 transports: [
9 //
10 // - Write all logs error (and below) to `error.log`.
11 new winston.transports.File({ filename: 'error.log', level: 'error' }),
12 //
13 // - Write to all logs with specified level to console.
14 new winston.transports.Console({ format: winston.format.combine(
15 winston.format.colorize(),
16 winston.format.simple()
17 ) })
18 ]
19 });
20
21 return async(ctx: Koa.Context, next: () => Promise<any>) => {
22
23 const start = new Date().getTime();
24
25 await next();
26
27 const ms = new Date().getTime() - start;
28
29 let logLevel: string;
30 if (ctx.status >= 500) {
31 logLevel = 'error';
32 } else if (ctx.status >= 400) {
33 logLevel = 'warn';
34 } else if (ctx.status >= 100) {
35 logLevel = 'info';
36 }
37
38 const msg: string = `${ctx.method} ${ctx.originalUrl} ${ctx.status} ${ms}ms`;
39
40 winstonInstance.log(logLevel, msg);
41 };
42}
4function initialiseLogger() {
5 const logger = createLogger({
6 level: config.get('logLevel'),
7 defaultMeta: { service: 'infrastructure-service' },
8 transports: [
9 new transports.Console({
10 format: format.combine(
11 format.json(),
12 format.timestamp(),
13 ),
14 }),
15 ],
16 });
17
18 if (process.env.NODE_ENV !== 'production') {
19 logger.clear();
20 logger.add(new transports.Console({
21 format: format.combine(
22 format.colorize(),
23 format.splat(),
24 format.simple(),
25 ),
26 }));
27 }
28 return logger;
29}
14function Logger(level, filename) {
15 const logLevel = level.toUpperCase() || 'INFO';
16
17 /* eslint-disable rapid7/static-magic-numbers */
18 const javaLogLevels = {
19 levels: {
20 ERROR: 0,
21 WARN: 1,
22 INFO: 2,
23 VERBOSE: 3,
24 DEBUG: 4,
25 SILLY: 5
26 },
27 colors: {
28 ERROR: 'red',
29 WARN: 'yellow',
30 INFO: 'green',
31 DEBUG: 'blue'
32 }
33 };
34
35 /* eslint-enable rapid7/static-magic-numbers */
36
37 const logger = new Winston.Logger({
38 level: logLevel,
39 levels: javaLogLevels.levels,
40 colors: javaLogLevels.colors,
41 transports: [
42 new Winston.transports.Console({
43 timestamp: true,
44 json: Config.get('log:json'),
45 stringify: Config.get('log:json'),
46 colorize: Config.get('colorize')
47 })
48 ]
49 });
50
51 if (filename) {
52 logger.add(Winston.transports.File, {filename, level});
53 deprecate('The file transport has been deprecated and will be removed in a later version');
54 }
55
56 return logger;
57}
11function createLogger(level, label) {
12 return new winston.Logger({
13 transports: [
14 new winston.transports.Console({
15 level: level,
16 timestamp: true,
17 colorize: LOGGING_CONFIG.colorize,
18 label: label || null
19 })
20 ]
21 });
22}
10export function getLogger(name: string, options?: any): Logger {
11 // TODO: Refactor options for logger (not for transport)
12 if (!loggers.has(name)) {
13 // add default Debug transport?
14 const defaultTransports = Object.keys(options || {}).length > 0 ? [] : [
15 new DebugTransport(options, name),
16 ];
17
18 loggers.add(name, {
19 exitOnError: false,
20 level: 'info',
21 format: format.combine(
22 format.splat(), // formats level.message based on Node's util.format().
23 format.label({ label: name }),
24 format.colorize(),
25 format.timestamp(),
26 format.printf(({ level, message, label, timestamp }) => `${timestamp} [${label}] ${level}: ${message}`)
27 ),
28 transports: defaultTransports,
29 });
30
31 loggers.get(name).on('error', (err: any) => {
32 if (err.code === 'ENOENT') {
33 let msg = err;
34 if (path.dirname(err.path) === '.') {
35 msg = 'Error from logger (winston) while trying to use a file to store logs:';
36 } else {
37 msg = 'Error from logger (winston) while trying to use a file to store logs, if the directory "'
38 + err.path + '" does not exists please create it:';
39 }
40 // make the error intentionally more visible to get the attention of the user
41 console.error('------------------------');
42 console.error(msg, err);
43 console.error('------------------------');
44 }
45 });
46 } else {
47 // remove all transports and add default Debug transport
48 loggers.get(name).clear();
49
50 if (Object.keys(options || {}).length === 0) {
51 loggers.get(name).add(new DebugTransport(options, name));
52 }
53 }
54
55 return loggers.get(name);
56}
37get logger(): winston.LoggerInstance {
38 return this._winston;
39}
22public setup(options: any): void {
23 if (!fs.existsSync(options.logDir)) fs.mkdirSync(options.logDir);
24
25 this._winston = new (winston.Logger)({
26 transports: [
27 new winston.transports.File({
28 filename: `${options.logDir}/${options.logFile}`,
29 level: env === 'development' ? 'debug' : 'info',
30 timestamp: tsFormat,
31 datePattern: 'yyyy-MM-dd'
32 })
33 ]
34 });
35}
25function setup() {
26 var env = process.env.NODE_ENV || 'development'
27 var logLevel = require('../config/settings')(env)['logLevel'] || 'debug'
28 sLogger = new winston.Logger({
29 levels: logLevels.levels,
30 colors: logLevels.colors,
31 level: logLevel,
32 transports: [
33 new (winston.transports.Console)()
34 ]
35 });
36 return sLogger
37}

Related snippets