Logging in JavaScript

Here’s the translation of the Go logging example to JavaScript, formatted in Markdown suitable for Hugo:

Our example demonstrates various logging techniques in JavaScript. We’ll use the built-in console object for basic logging and a third-party library called winston for more advanced structured logging.

First, let’s start with basic logging using the console object:

// Basic logging
console.log("standard logger");

// Logging with timestamp
console.log(new Date().toISOString(), "with timestamp");

// Logging with file and line information
console.log(new Error().stack.split("\n")[2].trim(), "with file/line");

// Creating a custom logger
const mylog = (prefix) => (message) => console.log(`${prefix}${message}`);
const customLogger = mylog("my:");
customLogger("from mylog");

// Changing the prefix
const newCustomLogger = mylog("ohmy:");
newCustomLogger("from mylog");

Now, let’s use a more advanced logging library, winston, for structured logging:

const winston = require('winston');

// Create a logger that writes to a buffer
const { Buffer } = require('buffer');
const streamBuffers = require('stream-buffers');
const myWritableStreamBuffer = new streamBuffers.WritableStreamBuffer();

const bufferLogger = winston.createLogger({
  transports: [
    new winston.transports.Stream({
      stream: myWritableStreamBuffer
    })
  ]
});

bufferLogger.info("hello");

// Print the contents of the buffer
console.log("from buflog:", myWritableStreamBuffer.getContentsAsString());

// JSON logging
const jsonLogger = winston.createLogger({
  format: winston.format.json(),
  transports: [
    new winston.transports.Console()
  ]
});

jsonLogger.info("hi there");

// Logging with additional key-value pairs
jsonLogger.info("hello again", { key: "val", age: 25 });

To run this example, you’ll need to install the required dependencies:

$ npm install winston stream-buffers
$ node logging.js

Sample output (the date and time emitted will depend on when the example ran):

standard logger
2023-08-22T17:45:16.904Z with timestamp
    at Object.<anonymous> (/path/to/logging.js:7:13) with file/line
my:from mylog
ohmy:from mylog
from buflog:{"message":"hello","level":"info"}
{"message":"hi there","level":"info"}
{"message":"hello again","level":"info","key":"val","age":25}

In JavaScript, we use the built-in console object for basic logging. For more advanced structured logging, we used the winston library, which provides similar functionality to Go’s slog package.

The console object provides methods like log(), info(), warn(), and error() for different log levels. We can add timestamps and other information manually.

For structured logging, winston allows us to create custom loggers with various transports (output destinations) and formats. We demonstrated logging to a buffer and logging in JSON format, similar to the Go example.

While JavaScript doesn’t have built-in support for logging to files or setting log flags like Go does, libraries like winston provide these features and more, allowing for flexible and powerful logging configurations.