1.0.6 • Published 4 years ago

@content-dynamics/logger v1.0.6

Weekly downloads
-
License
MIT
Repository
github
Last release
4 years ago

Simple logging for Node.Js with lots of config options.

Contents

Getting Started

To install easy-logger simply run npm install @content-dynamics/logger in your project.

To get started simply require and initalize the logger:

Logger = require('@content-dynamics/logger')()

The base logger has 4 base types:

Usage:

Logger.Log(message, { options })

Configuration

OptionsDescriptionDefault
levelInteger, controls the messages debug level1
debugBoolean or null, will override the level and add debug values to the log messagenull
importantBoolean, will override the logging level and print to consolefalse
flagsObject, Any additional properties you want to add to the debug message{}

Examples:

Logger.Log("By default this won't be logged to console or to the logging file");

Logger.Log("This will ensure that the info is logged to console and to the logging file",{ important: true });

Logger.Log("This will add a debug stack to the logging message and write it to the logging file and console",{ important:true, debug: true });

Usage:

Logger.Info(message, { options })

Configuration

OptionsDescriptionDefault
levelInteger, controls the messages debug level5
debugBoolean or null, will override the level and add debug values to the log messagenull
importantBoolean, will override the logging level and print to consolefalse
flagsObject, Any additional properties you want to add to the debug message{}

Examples:

Logger.Info("This will simply show as info in the log!");

Logger.Info("This will ensure that the info is logged to console",{ important: true });

Logger.Info("Thiswill add a debug stack to the warn message",{ debug: true });

Usage:

Logger.Warn(message, { options })

Configuration

OptionsDescriptionDefault
levelInteger, controls the messages debug level10
debugBoolean or null, will override the level and add debug values to the log messagenull
importantBoolean, will override the logging level and print to consolefalse
flagsObject, Any additional properties you want to add to the debug message{}

Examples:

Logger.Warn("This will simply show as a warning in the log!");

Logger.Warn("This will ensure that the warning is logged to console",{ important: true });

Logger.Warn("This won't add a stack to the warn message",{ debug: false });

Usage:

Logger.Error(message, { options })

Configuration

OptionsDescriptionDefault
levelInteger, controls the messages debug level20
debugBoolean or null, will override the level and add debug values to the log messagetrue
importantBoolean, will override the logging level and print to consoletrue
flagsObject, Any additional properties you want to add to the debug message{}

Examples:

Logger.Error("This will simply show as an error in the log!");

Logger.Error("This will set the debug message level to 50",{ level: 50 });

Logger.Error("This won't add a stack to the logged message",{ debug: false });

Advanced Configuration

The Logger instance can be defined with other options to match your requirements.

Example

const Logger = require('easylogger')({
    logFile:'./logs/main.log',
    logLevel:0,
    cmode:'json'})

The constructor takes several options passed through an object as defined below:

OptionDescriptionDefault Value
modeString, Logging Mode. Controls how data is logged to the logging file'json'
cmodeString, Console Logging Mode. Controls the logging of data to console'string'
logFileString, Path to the log file you want to use'./.log'
logLevelThe lowest level of logging message you would like to log to the logging file5
debugLevelThe lowest level you would like to automatically add debug info to10
consoleLevelThe lowest level you would like to automatically log to console15
preserveBoolean, If true preserve any previously saved logs in the log filefalse
streamFlagsObject, Any other fs.createWriteStream options you would like to use{}
dateFormatCallback, A callback used to format timestamps... Find out more...Function
logFormatCallback, A callback used to format the logging string... Find out more...Function Or util.inspect(message)
consoleFormatCallback, A Callback used to format the console string... Find out more...Function Or util.inspect(message)

Configuring dateFormat

The dateFormat option accepts a callback that takes the default "date-object" created by the helper function:

getDate()

The object returned from getDate() has the following properties:

Property NameTypeDescription
DAYObjectReturns an object containing 3 props: NUM, SHORT, LONG... Find out more...
DATEIntThe numeric date
MONTHIntThe numeric month
YEARIntThe numeric year
HOURIntThe numeric hour (24hr) of the day
MINUTEIntThe numeric minute of the hour
SECONDIntThe numeric second of the minute
TIMEZONEObjectReturns an object containing 3 props: HOURS, MINUTES, FULL... Find out more...

Example callback

dateFormat  = ( { DAY, DATE, MONTH, YEAR, HOUR, MINUTE, SECOND } )=>{
    return `[ ${DAY.SHORT} | ${DATE}:${MONTH}:${YEAR} | ${HOUR}:${MINUTE}:${SECOND} ]`;
},

Configuring logFormat

NameTypeDescription
prefixStringString prefix for the message
timestampStringString representaion of timestamp
levelIntThe level of the message
infoStringThe message text
debugMsgObject Or nullThe debug object or null, by default debugMsg will contain a prop: stack readmore

Example callback

logFormat = ( { prefix, timestamp, level, info, debugMsg } )=>{
    return `\n${prefix} - ${timestamp} - [LEVEL: ${level}]\nInfo:\n${info}${ debugMsg ? `\nDebug:${ inspect(debugMsg)}\n`:`\n`}`
}

Configuring consoleFormat

NameTypeDescription
prefixStringString prefix for the message
timestampStringString representaion of timestamp
levelIntThe level of the message
infoStringThe message text
debugMsgObject Or nullThe debug object or null, by default debugMsg will contain a prop: stack readmore

Example callback

consoleFormat = ( { prefix, timestamp, level, info, debugMsg } )=>{
    
    const formatMap = (num)=>{
        if (num >= 15) return {
            'prefix':chalk.bold.red,
            'timestamp':chalk.bold.red,
            'level':chalk.bold.red,
            'info':chalk.bold.yellow,
            'debug':chalk.yellow,
        }
        if (num >= 10) return {
            'prefix':chalk.bold.yellow,
            'timestamp':chalk.bold.yellow,
            'level':chalk.bold.yellow,
            'info':chalk.bold.white,
            'debug':chalk.yellow,
        }
        if (num >= 5) return {
            'prefix':chalk.bold.green,
            'timestamp':chalk.bold.green,
            'level':chalk.bold.green,
            'info':chalk.white,
            'debug':chalk.yellow,
        }
        return {
            'prefix':chalk.bold.green,
            'timestamp':chalk.green,
            'level':chalk.green,
            'info':chalk.white,
            'debug':chalk.white,
        }
    }

    const formatFromLevel = ( num, type, message)=>{
        return formatMap(num)[type](message);
    }

    const prefixFormatted = `${formatFromLevel(level, 'prefix', prefix)}`
    const timestampFormatted = `${formatFromLevel(level, 'timestamp', timestamp)}`;
    const levelFormatted = `${formatFromLevel(level, 'level', `[Level: ${level}]`)}`;
    const messageFormatted = `${formatFromLevel(level, 'info', `\nInfo:\n${info}\n`)}`;
    const debugFormatted = `${formatFromLevel(level, 'debug', `${debugMsg ? `\nDebug: ${ inspect(debugMsg)}\n`:''}`)}`;
    
    return `${prefixFormatted} - ${timestampFormatted} ${levelFormatted}\n${messageFormatted}${debugFormatted}`;
}

Further Reading

Stack Trace

The stack tracing function used by the logger returns an object with the following properties

NameTypeDescription
stackArrayAn array containing all the files within the stack trace.
calleeStringThe path to the calling function that initiated the logging

The Day object

The day object properties returned by getDate().DAY

PropertyDescription
NUMThe number of day in the week (0-60 is Sunday)
LONGA long string representation of the day
SHORTA short string representation of the day

The Timezone object

The timezone object properties returned by getDate().TIMEZONE

PropertyDescription
HOURSThe HOURLY GMT timezone difference
MINUTESThe MINUTE DIFFERENCE of HOURLY GMT timezone difference
FULLThe GMT timezone difference as string

Dependencies

Used to make console logging fun!

Used to test that the logger is working correctly during development

Contributing

Contributions to the project are more than welcome! Please visit the contributions guide for more information. Feel free to check the issues page if you want to contribute to solving issues.

If you would like to request a new feature please follow the request guide: Request a new feature

Author

:man_technologist: Elliot Gibson

License

Copyright 2021 Elliot Gibson. This project is licensed with the MIT license.

1.0.6

4 years ago

1.0.5

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago