How to use the createLogger function from bunyan

Find comprehensive JavaScript bunyan.createLogger code examples handpicked from public code repositorys.

bunyan.createLogger is a function that creates a new instance of a Bunyan logger, which is used for structured logging in Node.js applications.

102
103
104
105
106
107
108
109
110
111
112
113
  Object.keys(error).forEach((key) => (result[key] = error[key]));


  return result;
}


const log = bunyan.createLogger({
  name: 'snyk-broker',
  serializers: {
    token: sanitise,
    result: sanitise,
fork icon118
star icon81
watch icon0

74
75
76
77
78
79
80
81
82
83

constructor(serviceName = "polkaholic") {

    // Creates a Bunyan Cloud Logging client
    const loggingBunyan = new LoggingBunyan();
    this.logger = bunyan.createLogger({
        // The JSON payload of the log as it appears in Cloud Logging
        // will contain "name": "my-service"
        name: serviceName,
        streams: [
fork icon6
star icon21
watch icon2

+ 7 other calls in file

How does bunyan.createLogger work?

bunyan.createLogger works by returning a new instance of a Bunyan logger with the specified configuration options.

When called, bunyan.createLogger takes an object as an argument that specifies the configuration options for the new logger instance. These options typically include the logger's name, the level of log entries to output, any streams to write logs to (such as the console or a file), and any serializers to use for custom log data.

Once a new logger instance has been created with bunyan.createLogger, it can be used to log messages with various levels (such as "info", "debug", "error", etc.), along with any additional data to include in the log message.

The resulting logs are typically formatted as JSON objects, making them easy to parse and analyze with log processing tools like Elasticsearch, Logstash, or Kibana.

3
4
5
6
7
8
9
10
11
12
const bunyan = require('bunyan')
const path = require('path')
const promise = require('bluebird')
const cf = require('../../config.js')
const util = require('../util.js')
var log = bunyan.createLogger({
	name:'SQL',
	streams:[{
		level: 'info',
		type: 'rotating-file',
fork icon2
star icon4
watch icon0

+ 3 other calls in file

19
20
21
22
23
24
25
26
27
28
    app = loopback();
});

it('should use configured logger when loopback is initialized', function (done) {
    expect(app).to.have.property('loopback');
    var log = bunyan.createLogger({name: "myapp"});
    var rootLogger = logger(log);
    logger(app,{});
    expect(rootLogger.fields.name).to.equal('myapp');
    done();
fork icon0
star icon1
watch icon0

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const bunyan = require("bunyan");

// create a new logger instance
const logger = bunyan.createLogger({
  name: "myapp",
  level: "info",
  streams: [
    {
      stream: process.stdout,
      level: "info",
    },
    {
      type: "rotating-file",
      path: "./logs/myapp.log",
      level: "error",
      period: "1d",
      count: 7,
    },
  ],
});

// log some messages
logger.info("Server listening on port 3000");
logger.error("Failed to connect to database", {
  dbHost: "localhost",
  dbPort: 27017,
});

In this example, we're using bunyan.createLogger to create a new instance of a Bunyan logger with the name "myapp". We're also specifying that we want to log messages with a level of "info" or higher, and we want to output logs to both the console and a rotating file. We then use the logger.info and logger.error methods to log some example messages, including additional data (such as the database host and port) for the error message. As a result, the logger will output log messages in a JSON format to the console and a file, which could look like the following: json Copy code

4
5
6
7
8
9
10
11
12
13
14
const cors = require('cors');
const bunyan = require('bunyan');
const bunyanExpress = require('express-bunyan-logger');


// Setup logging
logger = bunyan.createLogger({
    name: 'poap-server',
    serializers: bunyan.stdSerializers,
    streams: [
        {
fork icon1
star icon0
watch icon1

+ 48 other calls in file

0
1
2
3
4
5
6
7
8
9
const { io } = require('socket.io-client');
const fs = require('fs');
const readline = require('readline');
const bunyan = require('bunyan');
const timestamp = new Date().getTime();
const connectionLog = bunyan.createLogger({
  name: `socket-pt`,
  streams: [
    {
      level: 'info',
fork icon0
star icon0
watch icon1

+ 119 other calls in file

188
189
190
191
192
193
194
195
196
197
                    statusCode: res.statusCode
                };
            }
        };
        // Create logger
        this.bunyanLog = bunyan.createLogger(options);
    }
    // Handle logging errors
    this.bunyanLog.on('error', this.handleStreamError.bind(this));
};
fork icon0
star icon0
watch icon2

+ 31 other calls in file

78
79
80
81
82
83
84
85
86
    opts.name = (opts.name || app.settings.shortname || app.settings.name || app.settings.title || 'express');
    opts.serializers = opts.serializers || {};
    opts.serializers.req = opts.serializers.req || bunyan.stdSerializers.req;
    opts.serializers.res = opts.serializers.res || bunyan.stdSerializers.res;
    err && (opts.serializers.err = opts.serializers.err || bunyan.stdSerializers.err);
    logger = bunyan.createLogger(opts);
}

var requestId;
fork icon0
star icon0
watch icon1

+ 7 other calls in file

30
31
32
33
34
35
36
37
38
39
40
41
42
43
];


const STACKSET_NAME_RE     = /^stackset\/(?<name>.+):(?<id>.+)$/;
const STATEMACHINE_NAME_RE = /^stateMachine:(?<name>.+)$/;


const log = bunyan.createLogger({ name: 'cweventFormat.handlebars' });




/**
 * Read a template file and compile it with Handlebars. This turns off HTML
fork icon0
star icon0
watch icon6

+ 2 other calls in file

214
215
216
217
218
219
220
221
222
223
224
225
		t.end();
	}, 1000);
});


test('\n\n ** Logging utility tests - test setting an external logger based on bunyan **\n\n', function (t) {
	var logger = bunyan.createLogger({ name: 'bunyanLogger' });
	hfc.setLogger(logger);


	testLogger(t);
	t.end();
fork icon0
star icon0
watch icon1

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


const DefaultLogID = 'VARA';
const KByte = 1 << 10;


const LogNothing = Bunyan.createLogger({
    name: 'VARA',
    level: Bunyan.FATAL + 100,
});

fork icon0
star icon0
watch icon1

+ 31 other calls in file

48
49
50
51
52
53
54
55
56
57
  return process_logger;
}

process_name = new_process_name;

parent_logger = bunyan.createLogger(
{
  name: process_name,
  serializers: bunyan.stdSerializers,
  streams: [
fork icon0
star icon0
watch icon1

93
94
95
96
97
98
99
100
101
102
  serviceContext : SquidObservabilityConfigs.serviceContext
});

// Create a Bunyan logger that streams to Cloud Logging
// Logs will be written to: "projects/YOUR_PROJECT_ID/logs/bunyan_log"
loggerSingleton = bunyan.createLogger({
  // The JSON payload of the log as it appears in Cloud Logging
  // will contain "name": "my-service"
  name        : SquidObservabilityConfigs.serviceContext.applicationName,
  serializers : {
fork icon0
star icon0
watch icon3

+ 14 other calls in file

33
34
35
36
37
38
39
40
41
42
//  try to remove sensitive info by default, e.g. 'password' fields
['formData', 'formValue'].forEach(keyName => {
    serializers[keyName] = fd => Log.hideSensitive(fd);
});

this.log = bunyan.createLogger({
    name: 'ENiGMA½ BBS',
    streams: logStreams,
    serializers: serializers,
});
fork icon0
star icon0
watch icon0

+ 3 other calls in file

15
16
17
18
19
20
21
22
23
24
25
26
const port = process.env.PORT || 7000;
// const timeout = require('connect-timeout')




// prepare log handler
const logger = bunyan.createLogger({ name: 'via-api-gateway',src:true });
delete logger.fields.hostname;
delete logger.fields.pid;
delete logger.fields.name;
delete logger.level;
fork icon0
star icon0
watch icon0

17
18
19
20
21
22
23
24
25
26
27
28
const ERROR_CODE_USER_COUNT_EMPTY = 202


const app = express();


// 创建一个日志记录器
const logger = bunyan.createLogger({
  name: "myapp",
  level: "error",
  streams: [{ path: "./myapp.log" }, { stream: process.stdout }],
});
fork icon0
star icon0
watch icon0

+ 3 other calls in file

2
3
4
5
6
7
8
9
10
11
12
13
14
const pjs = require('../../package.json');


// Get some meta info from the package.json
const { name, version } = pjs;


const getLogger = (serviceName, serviceVersion, level) => bunyan.createLogger({ name: `${serviceName}:${serviceVersion}`, level });


module.exports = {
  development: {
    sitename: 'Roux Meetups [Development]',
fork icon0
star icon0
watch icon0

8
9
10
11
12
13
14
15
16
17
18
const projectName = "auth";
const projectVersion = "1.0.0";
const env = process.env.ENV;


// Set up a logger
const getLogger = (serviceName, serviceVersion, level) => bunyan.createLogger({
    name: `${serviceName}:${serviceVersion}`,
    level
});

fork icon0
star icon0
watch icon0

3
4
5
6
7
8
9
10
11
12
13
14
15


// Get some meta info from package.json
const { name, version } = pjs;


// Set up a logger
const getLogger = (serviceName, serviceVersion, level) => bunyan.createLogger({ name: ` ${serviceName}: ${serviceVersion}`, level });


// Configuration option for different environment
module.exports = {
  development: {
fork icon0
star icon0
watch icon0

0
1
2
3
4
5
6
7
8
9
10
11
12
var express=require("express");
var app=express();


var bunyan = require("bunyan");
const LOG_LEVEL = process.env.LOG_LEVEL || "info";
var log = bunyan.createLogger({name: "diagnosis-search", level: LOG_LEVEL});


var axios=require("axios");


var port = process.env.PORT || 3000;
fork icon0
star icon0
watch icon0