Logging in TypeScript

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

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

First, let’s install the necessary dependencies:

npm install winston

Now, let’s look at the code:

import winston from 'winston';

function main() {
    // Simply using console.log, which is similar to the standard logger in Go
    console.log("standard logger");

    // Winston logger setup
    const logger = winston.createLogger({
        level: 'info',
        format: winston.format.combine(
            winston.format.timestamp(),
            winston.format.printf(({ timestamp, level, message }) => {
                return `${timestamp} ${level}: ${message}`;
            })
        ),
        transports: [
            new winston.transports.Console()
        ]
    });

    // Logging with microsecond precision
    logger.info("with micro");

    // Logging with file and line information
    Error.prepareStackTrace = (_, stack) => stack;
    const err = new Error();
    const callerLine = err.stack[1].getLineNumber();
    const callerFile = err.stack[1].getFileName();
    logger.info(`with file/line: ${callerFile}:${callerLine}`);

    // Creating a custom logger with a prefix
    const myLogger = winston.createLogger({
        format: winston.format.combine(
            winston.format.timestamp(),
            winston.format.printf(({ timestamp, level, message }) => {
                return `my:${timestamp} ${level}: ${message}`;
            })
        ),
        transports: [
            new winston.transports.Console()
        ]
    });

    myLogger.info("from myLogger");

    // Changing the prefix
    myLogger.format = winston.format.combine(
        winston.format.timestamp(),
        winston.format.printf(({ timestamp, level, message }) => {
            return `ohmy:${timestamp} ${level}: ${message}`;
        })
    );
    myLogger.info("from myLogger");

    // Logging to a string buffer
    let buffer = '';
    const bufLogger = winston.createLogger({
        format: winston.format.combine(
            winston.format.timestamp(),
            winston.format.printf(({ timestamp, level, message }) => {
                return `buf:${timestamp} ${level}: ${message}`;
            })
        ),
        transports: [
            new winston.transports.Stream({
                stream: {
                    write: (message: string) => {
                        buffer += message;
                    }
                }
            })
        ]
    });

    bufLogger.info("hello");
    console.log("from bufLogger:", buffer);

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

    jsonLogger.info("hi there");
    jsonLogger.info("hello again", { key: "val", age: 25 });
}

main();

This TypeScript code demonstrates various logging techniques:

  1. We start with a basic console.log, which is similar to the standard logger in other languages.

  2. We then set up a Winston logger with custom formatting to include timestamps.

  3. We show how to log with file and line information using the Error stack.

  4. We create a custom logger with a prefix and demonstrate how to change that prefix.

  5. We demonstrate logging to a string buffer.

  6. Finally, we show structured logging in JSON format.

To run this program, save it as logging.ts and use ts-node:

$ ts-node logging.ts

The output will look something like this (timestamps will vary):

standard logger
2023-08-22T17:45:16.904Z info: with micro
2023-08-22T17:45:16.905Z info: with file/line: /path/to/your/file/logging.ts:29
my:2023-08-22T17:45:16.905Z info: from myLogger
ohmy:2023-08-22T17:45:16.905Z info: from myLogger
from bufLogger: buf:2023-08-22T17:45:16.905Z info: hello
{"level":"info","message":"hi there","timestamp":"2023-08-22T17:45:16.905Z"}
{"level":"info","message":"hello again","timestamp":"2023-08-22T17:45:16.905Z","key":"val","age":25}

This example demonstrates various logging techniques in TypeScript, from basic console logging to more advanced structured logging using the Winston library.