How to use the format function from winston

Find comprehensive JavaScript winston.format code examples handpicked from public code repositorys.

Winston.format is a module in Node.js that provides utilities for formatting log messages in a desired way.

113
114
115
116
117
118
119
120
121
122
  // Running on Google Cloud, stream logs to Stackdriver.
  mainLogTransport = new LoggingWinston({prefix: label});
} else {
  // Running locally, stream logs to stdout.
  mainLogTransport = new winston.transports.Console({
    format: winston.format.combine(
        upperCaseLevel(),
        winston.format.timestamp(),
        winston.format.colorize(),
        formatForConsole
fork icon72
star icon140
watch icon33

+ 17 other calls in file

43
44
45
46
47
48
49
50
51
52
            maxsize: constants.MAX_LOG_SIZE_10_MB,
            maxFiles: 1,
            tailable: true,
            format: winston.format.combine(
                winston.format.timestamp(),
                winston.format.printf(formatLoggerOutput)
            )
        })
    ]
});
fork icon25
star icon84
watch icon18

+ 55 other calls in file

How does winston.format work?

winston.format is a module in the winston logging library that provides a set of pre-defined formatting functions and tools for creating custom formatting functions for log messages. The module offers methods for creating and composing formatting functions that can be applied to a log message before it is written to a log destination. The formatting functions can transform the log message into a desired format, add metadata, or enrich the message with additional information.

11
12
13
14
15
16
17
18
19
20
21
module.exports = CoreCommandRouter;
function CoreCommandRouter (server) {
  metrics.time('CommandRouter');


  this.logger = winston.createLogger({
    format: winston.format.simple(),
    transports: [
      new (winston.transports.Console)({level: 'verbose'})
    ]
  });
fork icon28
star icon21
watch icon4

90
91
92
93
94
95
96
97
98
99
  format.errors({ stack: true }),
  format.json(),
),
transports: [
  new transports.Console({
    format: winston.format.combine(winston.format.colorize(), myFormat),
  }),
  new transports.Http({
    level: "warn",
  }),
fork icon19
star icon62
watch icon4

+ 9 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
const winston = require("winston");

const myFormat = winston.format.printf(({ level, message, timestamp }) => {
  return `${timestamp} [${level}]: ${message}`;
});

const logger = winston.createLogger({
  level: "info",
  format: winston.format.combine(winston.format.timestamp(), myFormat),
  transports: [new winston.transports.Console()],
});

logger.info("This is a test log message");

In this example, winston.format.printf() is used to define a custom log format that includes the log level, message, and timestamp. The custom format is then combined with the built-in timestamp format using winston.format.combine(), and applied to a new logger instance using the format option. Finally, the logger is set up to use the built-in Console transport to output log messages to the console. When the info() method is called on the logger, it generates a log message using the custom log format.

251
252
253
254
255
256
257
258
259
260
Console: {
  format: winston.format.combine(winston.format.colorize(), winston.format.simple()),
  level: (process.env.NODE_ENV === 'development' ? 'verbose' : 'info')
},
DailyRotateFile: {
  format: winston.format.json(),
  dirname: path.join(__dirname, '..', 'logs'),
  filename: 'kano-%DATE%.log',
  datePattern: 'YYYY-MM-DD',
  maxFiles: '30d'
fork icon5
star icon15
watch icon5

13
14
15
16
17
18
19
20
21
22
  format: winston.format.json(),
  defaultMeta: { service: 'upload-b2' },
  transports: [
    new winston.transports.Console({
      level: 'debug',
      format: winston.format.simple()
    }),
    new winston.transports.File({ filename: 'error.log', level: 'error' })
  ]
})
fork icon5
star icon11
watch icon6

+ 7 other calls in file

11
12
13
14
15
16
17
18
19
20
    return undefined;
}
const logger = createLogger(); // create only one instance shared between all files
function createLogger() {
    if (rawLogFormat) {
        colorize = winston.format.colorize().colorize;
        // if colors updated ensure you update native colors also
        // black,red,green,yellow,blue,magenta,cyan,white,gray,grey,brightRed,brightGreen,brightYellow,brightBlue,brightMagenta,brightCyan,brightWhite
        winston.addColors({ error: 'brightRed', warn: 'brightYellow', info: 'brightBlue', debug: 'brightGreen' });
    }
fork icon4
star icon4
watch icon4

+ 18 other calls in file

181
182
183
184
185
186
187
188
189
190
}

if (env.LOGLEVEL === 'DEBUG') {
    logger.add(
        new winston.transports.Console({
            format: winston.format.json()
        }));
}

// Compulsory error handling
fork icon1
star icon12
watch icon7

+ 67 other calls in file

129
130
131
132
133
134
135
136
137
138
const logger = (module.exports = winston.createLogger({
    level: logLevel,
    transports: [new winston.transports.Console()],
    format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.colorize({
            all: true,
        }),
        winstonFormat,
    ),
fork icon1
star icon8
watch icon2

+ 31 other calls in file

15
16
17
18
19
20
21
22
23
24
        level: 'info',
        format: winston.format.combine(
            winston.format.errors({ stack: true }),
            winston.format.timestamp(),
            winston.format.colorize(),
            winston.format.simple(),
            winston.format.printf((info) => `${info.timestamp} ${info.level}: ${info.message}`)
        ),
    })
);
fork icon2
star icon7
watch icon2

+ 39 other calls in file

227
228
229
230
231
232
233
234
235
236

if ( !fs.existsSync( logDir ) ) {
    fs.mkdirSync( logDir );
}

const { combine, timestamp, label, printf, splat } = winston.format;

const logFormat = printf(({ level, message, durationMs, timestamp }) => {
    if (typeof durationMs !== 'undefined') {
        return `${timestamp} ${level}: [${durationMs}ms]: ${message}`;
fork icon1
star icon5
watch icon6

26
27
28
29
30
31
32
33
34
35
36
    }
})


const logConfiguration = {
    level: 'info',
    // format: winston.format.json(),
    format: winston.format.simple(),
    // defaultMeta: { service: 'user-service' },
    transports: [
        //
fork icon1
star icon2
watch icon0

+ 2 other calls in file

166
167
168
169
170
171
172
173
174
175
return winston.createLogger({
  level: CONFIG.options.logLevel,
  format: winston.format.combine(
    winston.format.splat(),
    winston.format.timestamp(),
    winston.format.printf(({level, message, timestamp}) => {
      return `${timestamp} ${level}: ${message}`;
    })
  ),
  transports: [
fork icon1
star icon1
watch icon1

+ 75 other calls in file

2
3
4
5
6
7
8
9
10
11
12
const winston = require('winston');
const dayjs = require('dayjs');
let today = dayjs();


const logger = winston.createLogger({
    format: winston.format.printf((info) => {
        return `${today.format("YYYY-MM-DD h:mm:ss")} [${info.level}] spark.regex | ${info.message}`
    }),
    transports: [
        new winston.transports.Console()
fork icon1
star icon1
watch icon0

+ 4 other calls in file

3
4
5
6
7
8
9
10
11
12
// initialize logger
    const logger = winston.createLogger({
    level: 'info',
    format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.json(),
        winston.format.printf(info => `{"timestamp":"${info.timestamp}", "topic":"${info.topic}", "level":"${info.level}", "message":"${info.message}"}`)
    ),
    topic: undefined,
    transports: [
fork icon0
star icon1
watch icon1

+ 11 other calls in file

23
24
25
26
27
28
29
30
31
32
    new winston.transports.Console(),
    new winston.transports.File({ filename: "logs/latest.log" })
],
format: winston.format.combine(
    winston.format.colorize(),
    winston.format.json()
),
meta: false,
msg: "HTTP  ",
expressFormat: true,
fork icon0
star icon1
watch icon1

+ 5 other calls in file

18
19
20
21
22
23
24
25
26
27
logger.add(
    new winston.transports.Console({
        format: winston.format.combine(
            winston.format.colorize(),
            winston.format.timestamp(),
            winston.format.printf((info) => `${info.timestamp} ${info.level}${info.label ? ` [${info.label || ""}]` : ""}: ${info.message}`)
        ),
        level: process.env.LOGGING_LEVEL || "silly",
    })
);
fork icon0
star icon1
watch icon0

+ 3 other calls in file

111
112
113
114
115
116
117
118
119
120
// })

const logConfiguration = {
  transports: [rotateTransport, errorTransport],
  format: winston.format.combine(
    winston.format.timestamp({
      format: 'YYYY-MM-DDTHH:mm:ss',
    }),
    winston.format.colorize(),
    winston.format.printf(info =>
fork icon0
star icon0
watch icon1

+ 63 other calls in file

5
6
7
8
9
10
11
12
13
14
15
const winston = require('winston');


const logger = module.exports = winston.createLogger({
  transports: [new winston.transports.Console()],
  format: winston.format.combine(
    winston.format.colorize({ all: true }),
    winston.format.simple()
  )
});

fork icon0
star icon0
watch icon1

+ 47 other calls in file

21
22
23
24
25
26
27
28
29
30
31
32


const filename = path.join('./', 'combined.log');


const logger = winston.createLogger({
  levels: winston.config.syslog.levels,
  format: winston.format.combine(winston.format.colorize(), winston.format.timestamp({format: 'YYYY-MM-DD HH:mm:ss'}), winston.format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)),
  transports: [
    new winston.transports.File({
      filename: filename,
      maxsize: 10000000,
fork icon0
star icon0
watch icon1

+ 20 other calls in file