Introduction
Simple logging module written in TypeScript.
Levels
There are 5 log levels:
const Logger = LoggerLevelDEBUGLoggerLevelINFOLoggerLevelWARNLoggerLevelERRORLoggerLevelOFF
Logging to the console
The following code creates a logger object that writes to stdout
and stderr in the format [dd/mm/yyyy hh:mm:ss][LEVEL][TAG]: message]
:
const Logger = const logger = tag: "Logger1" level: LoggerLevelDEBUG format: LoggerFormatstandard; logger;logger;logger;logger;
If you would like colours and your terminal supports it, replace
Logger.Format.standard
with Logger.Format.standardColoured
Logging to a file
The following code creates a logger object that writes to a file stream of your choice, in the same format as above
const fs = ;const Logger = const logger = tag: "Logger2" level: LoggerLevelDEBUG format: LoggerFormatstandard file: fs;
Chaining loggers
Often you could find yourself wanting to log the
same data to two or more different output, you can do this
by using the chain method of the Logger
prototype
const Logger = ; const logger1 = ...;const logger2 = ...;const logger3 = ...; logger1 logger1;// logs to logger2 and logger3 as well logger2;// logs to logger3, but not logger1
Creating your own format
Format functions receive a LogData
object:
;
Just to clarify, since the others are self explanatory, items is just an array of whatever the calling code wanted to log.
Your function should look something like this:
{ // create output here // return string}
Then you can pass this function around to all your loggers that need to use it.
Creating your own Logger
If the included implemenations don't quite fit your needs you can always implement your own and keep the same public interface.
const Logger = ; Abstract { // whatever needs to happen to log 'message' }
Logger factories
Sometimes you may not want to use a single logger with the same tag and level. A function that you can import everywhere a logger is needed is great for creating a bunch of similar logger objects.
For example, a lot of files I have only need Logger.Console
and
they should all have the same level and format, but a different tag.
const Logger = ;const level = LoggerLevelINFO;const format = LoggerFormatstandardColoured; { return tag level format ;} moduleexports = createLogger;
You could also do something similar to return different types of Logger
's