Winston Logging - separate levels to separate Transports

前端 未结 3 1544

I am using Winston for logging with 2 different transports - File and MongoDB. I have set the level for File as \"INFO\" and for MongoDB as \"ERROR\". If I now log,



        
3条回答
  •  长情又很酷
    2021-01-21 12:50

    had a similiar issue and this is what I came up with. This can be done by just setting the log functions to empty functions. This is some code of mine I modified that did something similiar. This code takes customSilenceLevelLow and customSilenceLevelHigh and any log function with a value lower or equal to customSilenceLevelLow gets set to an empty function and any log function with value higher or equal to customSilenceLevelHigh gets set to an empty function

    so in this code only logs of level info,info2 and info3 get logged to console. the rest do not.

    NOTE: I didnt test these changes so there could be some syntax errors but the logic should be good.

    winston = require("winston") 
    
    var levels = {levels: {
        debug: 0,
        debug2: 1,
        debug3: 2,
        verbose: 3,
        verbose2: 4,
        verbose3: 5,
        info: 6,
        info2: 7,
        info3: 8,
        silly: 9,   
        warn: 10,
        error: 11
    },
    colors: {
        debug: "blue",
        debug2: "cyan",
        debug3: "grey",
        verbose: "cyan",
        verbose2: "magenta",
        verbose3: "blue",
        info: "green",
        info2: "magenta",
        info3: "grey",
        silly: "green", 
        warn: "yellow",
        error: "red"
    }}
    
    //needed so that new levels and colors are recognized       
    winston.setLevels(levels.levels)
    winston.addColors(levels.colors);
    
    //add color to log text
    winston.default.transports.console.colorize = true
    winston.default.transports.console.prettyPrint = true
    
    //false is default silences transport
    winston.default.transports.console.silent = false
    
    winston.default.transports.console.level = "debug"
    
    var customSilenceLevelLow = "info"
    var customSilenceLevelHigh = "info3"
    
    for (var k in levels.levels) {
    
        if (levels.levels[k] <= levels.levels[customSilenceLevelLow] || levels.levels[k] >= levels.levels[customSilenceLevelHigh]) {
    
            //create an empty function to silence logs
            winston[k] = function () {}
        }   
    }
    

提交回复
热议问题