pinojs/pino

[question] How do I create dynamic customized logfile names?

Opened this issue · 3 comments

Hi there,
I'm new to pino so sorry if my question is very basic.

I'm trying to use a custom transport to log to a file with this format: application-<year>-<month>-<date>.log
I want it to switch files when the day ends / transfers.

Currently I have this in my custom transport:

import { createWriteStream } from "fs";

const pad = num => (num > 9) ? num : `0${num}`;

export default (options) => {
    const filename = generateFileName(options.filename);

    return createWriteStream(filename, { flags: 'a' });
}

function generateFileName(filenameParams) {
    const currentDate = new Date();

    const filename = filenameParams
        .replace('<year>', currentDate.getFullYear())
        .replace('<month>', pad(currentDate.getMonth() + 1))
        .replace('<date>', pad(currentDate.getDate()))
    
    return filename;
}

My logger:

const absolutePath = path.resolve(__dirname, './test.mjs');

const transport = pino.transport({
     target: absolutePath,
     options: { filename: 'application-<year>-<month>-<date>.log'}
 })

this.#logger = pino(transport)

This works for the first file but not for subsequent dates.
I understand this is because the custom transport is only called once on initialization and not each time the write functionality is called.

I've been scouring the net for examples for my use case to no avail. Help would be much appreciated.

I recommend utilizing your system tools to do this https://getpino.io/#/docs/help?id=rotate

check out the pino-roll module.

Hey guys,
thanks for the replies. I'm trying out using my system tools for now using a VM, but I'll take a look at the pino-roll module too.
Thanks a bunch!