# Custom logger in settings.js to write the logs to a filesystem?

**URL:** <https://discourse.nodered.org/t/custom-logger-in-settings-js-to-write-the-logs-to-a-filesystem/74678>\
**Category:** General\
**Created:** [3 February 2023 21:07 UTC](https://discourse.nodered.org/t/custom-logger-in-settings-js-to-write-the-logs-to-a-filesystem/74678 "2023-02-03T21:07:57Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![Josh](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/josh/32/62208_2.png) [@Josh](https://discourse.nodered.org/u/Josh)\
**Post date:** [3 February 2023 21:07 UTC](https://discourse.nodered.org/t/custom-logger-in-settings-js-to-write-the-logs-to-a-filesystem/74678/1 "2023-02-03T21:07:57Z")

</div>

Hi,  
I am looking out for a solution on how to write nodered logs to filesystem. I tried using the logger in settings.js but couldnt find an appropriate way to do that. Please Help !!

---

<div class="post-metadata">

**Author:** ![marcus-j-davies](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/marcus-j-davies/32/103435_2.png) [@marcus-j-davies](https://discourse.nodered.org/u/marcus-j-davies)\
**Post date:** [3 February 2023 21:44 UTC](https://discourse.nodered.org/t/custom-logger-in-settings-js-to-write-the-logs-to-a-filesystem/74678/2 "2023-02-03T21:44:53Z")

</div>

Hi @Josh

You shouldn't need to resort to changing things in settings.js.  
the `function` node exposes.

- node.log()
- node.warn()
- node.error()

That should, under normal circumstances, output to the corresponding log file.

see below:

 ![Screenshot 2023-02-03 at 21.38.51](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/9/a/9a241fe04ed2ba6d85ec93d9c3a4e5d14c34a9ab.png)

---

<div class="post-metadata">

**Author:** ![Colin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/colin/32/17040_2.png) [@Colin](https://discourse.nodered.org/u/Colin)\
**Post date:** [3 February 2023 22:12 UTC](https://discourse.nodered.org/t/custom-logger-in-settings-js-to-write-the-logs-to-a-filesystem/74678/3 "2023-02-03T22:12:38Z")

</div>

Or perhaps node-red-contrib-flogger will do what you want.

---

<div class="post-metadata">

**Author:** ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)\
**Post date:** [3 February 2023 23:34 UTC](https://discourse.nodered.org/t/custom-logger-in-settings-js-to-write-the-logs-to-a-filesystem/74678/4 "2023-02-03T23:34:42Z")

</div>

I don't have exactly what you want. But I do have an example that writes to MQTT and that outputs trace logging but only for uibuilder (of course, you could change the filter to whatever you wanted).

Also included, but commented out is an example of logging to a Winston instance which might be of interest. I can't remember whether I stole it with pride from someone I'm afraid. Not even sure it actually works but anyway, might be a starting point.

```auto
    logging: {
        console: {
            /** Level of logging to be recorded. Options are:
             * fatal - only those errors which make the application unusable should be recorded
             * error - record errors which are deemed fatal for a particular request + fatal errors
             * warn - record problems which are non fatal + errors + fatal errors
             * info - record information about the general running of the application + warn + error + fatal errors
             * debug - record information which is more verbose than info + info + warn + error + fatal errors
             * trace - record very detailed logging + debug + info + warn + error + fatal errors
             * off - turn off all logging (doesn't affect metrics or audit)
             */
            level: 'info',
            /** Whether or not to include metric events in the log output */
            metrics: false,
            /** Whether or not to include audit events in the log output */
            audit: false,
        },
        /** Custom logging: https://nodered.org/docs/user-guide/runtime/logging */

        // winstonLog: {
        // level: 'trace',
        // metrics: false,
        // audit: false,
        // handler: function(settings) {
        // // const winstond = require('winstond')

        // // const server = winstond.nssocket.createServer({
        // // services: ['collect', 'query', 'stream'],
        // // port: 9003
        // // });

        // // server.add(winstond.transports.File, {
        // // filename: __dirname + '/foo.log'
        // // })

        // // server.listen()

        // // const winston = require('winston')
        // // require('winston-mqtt').MqttTransport

        // const myCustomLevels = {
        // levels: {
        // 'FATAL':10, 
        // 'ERROR':20, 
        // 'WARN ':30, 
        // 'INFO ':40, 
        // 'DEBUG':50, 
        // 'TRACE':60, 
        // 'AUDIT':98, 
        // 'MTRIC':99
        // },
        // colors: {
        // 'FATAL':'redBG', 
        // 'ERROR':'red', 
        // 'WARN ':'orange', 
        // 'INFO ':'yellow', 
        // 'DEBUG':'green', 
        // 'TRACE':'cyan', 
        // 'AUDIT':'grey', 
        // 'MTRIC':'grey'
        // }
        // }

        // // winston.add(require('winston-nssocket').Nssocket, {
        // // host: 'localhost',
        // // port: 9003
        // // })

        // // const { combine, timestamp, label, printf, splat, prettyPrint, colorize } = winston.format

        // // const myFormat = printf(({ level, message, label, timestamp }) => {
        // // //return `${timestamp} ${level}| [${label}] ${message}`
        // // return `${level}| ${message.replace('[uibuilder:','[')}`
        // // })

        // // var mylog = winston.createLogger({
        // // levels: myCustomLevels.levels, //winston.config.npm.levels, //
        // // level: 'TRACE',
        // // transports: [
        // // //new winston.transports.Console({ format: winston.format.simple() }),
        // // new winston.transports.File({ filename: 'uibuilder1.log' }),
        // // new winston.transports.Http({ // https://github.com/winstonjs/winston/blob/HEAD/docs/transports.md#http-transport
        // // host: 'localhost',
        // // port: 1880,
        // // path: '/nr/winston',
        // // // auth, ssl
        // // }),
        // // new winston.transports.MqttTransport, {
        // // name: 'node-red',
        // // topic: 'log',
        // // host: 'mqtt://localhost:1883',
        // // // requestTracer: {
        // // // instance: myRequestObject,
        // // // property: 'requestId'
        // // // }
        // // }
        // // ],
        // // // https://github.com/winstonjs/logform#readme
        // // format: combine(
        // // //label({ label: 'right meow!' }),
        // // //timestamp(),
        // // colorize({ colors: myCustomLevels.colors, all:true }),
        // // prettyPrint(),
        // // myFormat
        // // ),
        // // })

        // // mylog.log({
        // // 'level': 'TRACE',
        // // 'message': 'Hello'
        // // })

        // // winston.stream().on('log', function (log) {
        // // console.log(log);
        // // });

        // // winston.query({ start: 10 }, function (err, results) {
        // // if (err) throw err;
        // // console.log(results);
        // // });

        // const nrLogLevels = {
        // 10: 'FATAL', 20: 'ERROR', 30: 'WARN ', 40: 'INFO ', 50: 'DEBUG', 60: 'TRACE', 98: 'AUDIT', 99: 'MTRIC'
        // }

        // // return function(msg) {
        // // if ( msg.level < 51 || msg.msg.includes('[uibuilder') || msg.msg.startsWith('+-') || msg.msg.startsWith('| ') || msg.msg.startsWith('>>') ) {
        // // mylog.log({
        // // 'level': nrLogLevels[msg.level],
        // // 'message': msg.msg
        // // })
        // // }
        // // }
        // }
        // },
        mqttLog: {
            level: 'trace',
            metrics: false,
            audit: false,
            handler: function(settings) {
                const nrLogLevels = {
                    10: 'FATAL', 20: 'ERROR', 30: 'WARN ', 40: 'INFO ', 50: 'DEBUG', 60: 'TRACE', 98: 'AUDIT', 99: 'MTRIC'
                }
                const myCustomLevels = {
                    levels: {
                        'FATAL':10, 
                        'ERROR':20, 
                        'WARN ':30, 
                        'INFO ':40, 
                        'DEBUG':50, 
                        'TRACE':60, 
                        'AUDIT':98, 
                        'MTRIC':99
                    },
                    colors: {
                        'FATAL':'redBG', 
                        'ERROR':'red', 
                        'WARN ':'orange', 
                        'INFO ':'yellow', 
                        'DEBUG':'green', 
                        'TRACE':'cyan', 
                        'AUDIT':'grey', 
                        'MTRIC':'grey'
                    } 
                }

                const mqtt = require('mqtt')
                const client = mqtt.connect('mqtt://home.knightnet.co.uk')

                return function(msg) {
                    if ( msg.level < 51 || msg.msg.includes('[uibuilder') || msg.msg.startsWith('+-') || msg.msg.startsWith('| ') || msg.msg.startsWith('>>') ) {
                        client.publish( 'nrlog/dev', JSON.stringify(msg) )
                    }
                }
            }
        },
    },

```

---

<div class="post-metadata">

**Author:** ![marcus-j-davies](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/marcus-j-davies/32/103435_2.png) [@marcus-j-davies](https://discourse.nodered.org/u/marcus-j-davies)\
**Post date:** [3 February 2023 23:40 UTC](https://discourse.nodered.org/t/custom-logger-in-settings-js-to-write-the-logs-to-a-filesystem/74678/5 "2023-02-03T23:40:12Z")

</div>

> [@TotallyInformation](#):
>
> Winston instance which might be of interest.

I use winston quite a bit.  
I use a Node lib that allows adding Winston 'transports' to its framework - so added a transport to send logs out to a 2nd pin.

very versatile

---

<div class="post-metadata">

**Author:** ![Josh](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/josh/32/62208_2.png) [@Josh](https://discourse.nodered.org/u/Josh)\
**Post date:** [5 February 2023 15:23 UTC](https://discourse.nodered.org/t/custom-logger-in-settings-js-to-write-the-logs-to-a-filesystem/74678/6 "2023-02-05T15:23:38Z")

</div>

@TotallyInformation I have done as per what you have said and it seems Im having trouble starting the Node-Red. I am trying with the winston instance and it would be a great help if you could let me know which part of code is necessary for that operation.

---

<div class="post-metadata">

**Author:** ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)\
**Post date:** [5 February 2023 16:22 UTC](https://discourse.nodered.org/t/custom-logger-in-settings-js-to-write-the-logs-to-a-filesystem/74678/7 "2023-02-05T16:22:51Z")

</div>

I think you will need to share what errors you are getting. I don't use Winston actively.

---

<div class="post-metadata">

**Author:** ![Josh](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/josh/32/62208_2.png) [@Josh](https://discourse.nodered.org/u/Josh)\
**Post date:** [6 February 2023 12:31 UTC](https://discourse.nodered.org/t/custom-logger-in-settings-js-to-write-the-logs-to-a-filesystem/74678/8 "2023-02-06T12:31:49Z")

</div>

I am getting Error loading settings while I try to run the Script.

---

<div class="post-metadata">

**Author:** ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)\
**Post date:** [6 February 2023 17:01 UTC](https://discourse.nodered.org/t/custom-logger-in-settings-js-to-write-the-logs-to-a-filesystem/74678/9 "2023-02-06T17:01:05Z")

</div>

Sorry Josh but that doesn't really help. We would need to see the actual errors to have any hope of understanding what was happening.

---

<div class="post-metadata">

**Author:** ![Josh](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/josh/32/62208_2.png) [@Josh](https://discourse.nodered.org/u/Josh)\
**Post date:** [7 February 2023 05:12 UTC](https://discourse.nodered.org/t/custom-logger-in-settings-js-to-write-the-logs-to-a-filesystem/74678/10 "2023-02-07T05:12:13Z")

</div>

Apologies for the late response. I did solve the problem using the 'Pino' Module. Anyways @TotallyInformation your approach led me straight in solving this problem.

Please find the attached code.

Note: Please install the required npm packages

```auto
var pino = require('pino');
var fs = require('fs');

var rotatingLogStream = require('file-stream-rotator').getStream({filename:"./path_%DATE%",frequency:"custom",verbose: false ,size:"100M", max_logs: "10d", audit_file:"./path/logaudit.json",date_format: "YYYY-MM-DD-A",extension:".log"});

rotatingLogStream.on('rotate',function(oldFile,newFile){
    console.log("Rotate",oldFile)
})

var logger = pino({}, rotatingLogStream);

module.exports ={
console: {
             /** Level of logging to be recorded. Options are:
              * fatal - only those errors which make the application unusable should be recorded
              * error - record errors which are deemed fatal for a particular request + fatal errors
              * warn - record problems which are non fatal + errors + fatal errors
              * info - record information about the general running of the application + warn + error + fatal errors
              * debug - record information which is more verbose than info + info + warn + error + fatal errors
              * trace - record very detailed logging + debug + info + warn + error + fatal errors
              * off - turn off all logging (doesn't affect metrics or audit)
              */
             level: "debug",
             /** Whether or not to include metric events in the log output */
             metrics: false,
             /** Whether or not to include audit events in the log output */
             audit: true
         },
         customlogger: {
            level: 'debug',
            metrics: false,
            audit: false,
            handler: function (settings) {
                return function (log) {
                    switch (log.level) {
                        case 'fatal':
                            logger.fatal(log.msg);
                            break;
                        case 'error':
                            logger.error(log.msg);
                            break;
                        case 'warn':
                            logger.warn(log.msg);
                            break;
                        case 'info':
                            logger.info(log.msg);
                            break;
                        case 'debug':
                            logger.debug(log.msg);
                            break;
                        case 'trace':
                            logger.trace(log.msg);
                            break;
                        default:
                            logger.info(log.msg);
                            break;
                    }
                };
            }
        }
}

```

---

<div class="post-metadata">

**Author:** ![Josh](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/josh/32/62208_2.png) [@Josh](https://discourse.nodered.org/u/Josh)\
**Post date:** [7 February 2023 05:13 UTC](https://discourse.nodered.org/t/custom-logger-in-settings-js-to-write-the-logs-to-a-filesystem/74678/11 "2023-02-07T05:13:54Z")

</div>

This is something I did consider while developing. Thanks for the info 😃

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)\
**Post date:** [21 February 2023 05:14 UTC](https://discourse.nodered.org/t/custom-logger-in-settings-js-to-write-the-logs-to-a-filesystem/74678/12 "2023-02-21T05:14:13Z")

</div>

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
