@auturge/logger
v1.0.3
Published
A handy multiplexing logger.
Downloads
5
Readme
auturge/logger
This readme is incomplete.
I'm working on it, but I also have to sleep sometimes! :sleeping:
Installation
$ npm install @auturge/logger
(go to top)
Introduction
I needed a quick way to log messages to the console or terminal with custom formatting (like colored success, error, and warning messages). Something like log4xxx, or nLog, but for TypeScript/javascript.
I felt like reinventing the wheel (so naughty), so here's a handy, extensible logger library.
(go to top)
Examples
Use the default "Log" to log a message
import { Log } from '@auturge/logger';
Log.info('Doing a thing...');
... which is shorthand for...
Create and configure a single console logger at the TRACE level
import { LogManager, TERMINAL, LogLevel } from '@auturge/logger';
const logger = LogManager.initialize
.newChannel('terminal', TERMINAL, LogLevel.INFO)
.andGetLogger();
logger.info('Doing a thing...');
... or you could do something a little more complicated:
Create and configure a multiplexing logger
import {
LogManager, TerminalWriter, DateFormat, LogLevel, IWriter
} from '@auturge/logger';
import { MyFileWriter } from 'whatever-file-you-put-it-in';
// use the included terminal writer
const TERMINAL: IWriter = new TerminalWriter(` %{ date | ${ DateFormat.DEFAULT } } | %{level} | %{message}`);
// write your own file-writer
const MY_FILE_WRITER: IWriter = new MyFileWriter('%{date} | %{level} | %{message}');
const logger = LogManager.initialize
.newChannel('terminal', LogLevel.INFO, TERMINAL)
.newChannel('file', LogLevel.TRACE, MY_FILE_WRITER)
.andGetLogger();
logger.error('Look! An error which will appear in both logs...', error);
logger.info('Look! A log entry which will appear in both logs...');
logger.trace('Look! An entry that will only appear in the debug log file...');
(go to top)
API
There are several abstraction exposed by @auturge/logger:
There are also several class instances:
...and a number of enums:
(go to top)
Abstractions
@auturge/logger exposes several abstractions, designed to make the library extensible:
(go to top)
ILog
ILog
: An interface describing the properties and methods used to log messages.
Any ILog<TLog, TEntry>
exposes the following members:
along with several logging-specific methods:
Unfortunately Github Flavored Markdown (GFM) does not support custom text colors wtihout using hacky workarounds or placeholder sites, so I won't demo colors here, but instead provide a table:
|Method|Color| |:---|:---| |fatal|red| |error|red| |warn|yellow| |info|default console color| |debug|cyan| |trace|default console color|
(go to top)
fatal
ILog.fatal(message: string): void; ILog.fatal(message: string, obj: any): void; ILog.fatal(message: string, obj: any, prettyPrint: boolean): void;
Formats and writes a fatal log message.
This is the log level that tells the user that the application has encountered an event or entered a state in which one of the crucial business functionalities is no longer working. A FATAL log level may be used when the application is not able to connect to a crucial data store like a database or all the payment systems are not available and users can’t checkout their baskets in your e-commerce.
(go to top)
error
ILog.error(message: string): void; ILog.error(message: string, obj: any): void; ILog.error(message: string, obj: any, prettyPrint: boolean): void;
Formats and writes an error log message.
This tells the user that the application has hit an issue preventing one or more functionalities from properly functioning. The ERROR level can be used when one of the payment systems is not available, but there is still the option to check out the basket in the e-commerce application or when your social media logging option is not working for some reason.
(go to top)
warn
ILog.warn(message: string): void; ILog.warn(message: string, obj: any): void; ILog.warn(message: string, obj: any, prettyPrint: boolean): void;
Formats and writes a warning log message.
This tells the user that something unexpected happened in the application: a problem, or a situation that might disturb one of the processes. But that doesn’t mean that the application failed. The WARN level should be used in situations that are unexpected, but the code can continue the work. For example, a parsing error occurred that resulted in a certain document not being processed.
(go to top)
info
ILog.info(message: string): void; ILog.info(message: string, obj: any): void; ILog.info(message: string, obj: any, prettyPrint: boolean): void;
Formats and writes an informational log message.
This is the standard log level indicating that something happened, the application entered a certain state, etc. For example, a controller of your authorization API may include an INFO log entry with information on which user requested authorization if the authorization was successful or not. The information logged using the INFO log level should be purely informative and not looking into them on a regular basis shouldn’t result in missing any important information.
(go to top)
debug
ILog.debug(message: string): void; ILog.debug(message: string, obj: any): void; ILog.debug(message: string, obj: any, prettyPrint: boolean): void;
Formats and writes a debug log message.
This level is less granular compared to the TRACE level, but it is more than you will need in everyday use. The DEBUG log level should be used for information that may be needed for diagnosing issues and troubleshooting or when running application in the test environment for the purpose of making sure everything is running correctly
(go to top)
trace
ILog.trace(message: string): void; ILog.trace(message: string, obj: any): void; ILog.trace(message: string, obj: any, prettyPrint: boolean): void;
Formats and writes a trace log message.
This level is for the most fine-grained information only used in rare cases where you need the full visibility of what is happening in your application and inside the third-party libraries that you use. You can expect the TRACE logging level to be very verbose. You can use it for example to annotate each step in the algorithm or each individual query with parameters in your code.
(go to top)
Instances
@auturge/logger exposes several 'default' implementations of the provided abstractions:
(go to top)
Log
Log: A default terminal logger for quick out-of-the-box logging.
Any ILog
exposes the following methods:
The Log
is an IStatusLog
, a special type of ILog
which also exposes the following logging methods:
In addition, Log
will colorize each log entry.
Unfortunately Github Flavored Markdown (GFM) does not support custom text colors wtihout using hacky workarounds or placeholder sites, so I won't demo colors here, but instead provide a table:
|Method|Color| |:---|:---| |fatal|red| |error|red| |warn|yellow| |info|default console color| |debug|cyan| |trace|default console color| |success|green| |failure|red| |mark|magenta|
(go to top)
success
IStatusLog.success(message: string): void; IStatusLog.success(message: string, obj: any): void; IStatusLog.success(message: string, obj: any, prettyPrint: boolean): void;
Formats and writes a success log message.
This is for informing the user of some significant operational success.
Some examples of success
messages:
- 'All done!'
- 'Successfully logged in!'
NOTE:
success
entries are logged at theinfo
level.Setting the level of the logger higher than
info
will filter out anysuccess
messages.
(go to top)
failure
IStatusLog.failure(message: string): void; IStatusLog.failure(message: string, obj: any): void; IStatusLog.failure(message: string, obj: any, prettyPrint: boolean): void;
Formats and writes a trace log message.
This is for informing the user of some significant operational failure that is tied to user action. Failure messages represent user errors, not exceptional code failures (for that, use error
or fatal
).
Some examples of failure
messages:
- 'Failed to log in!' (due to an HTTP 401 error, not a 500)
- 'Passwords must include at least 12 letters (both upper- and lowercase), at least 1 number, and at least 1 symbol.'
NOTE:
failure
entries are logged at theinfo
level.Setting the level of the logger higher than
info
will filter out anyfailure
messages.
(go to top)
mark
IStatusLog.mark(message: string): void; IStatusLog.mark(message: string, obj: any): void; IStatusLog.mark(message: string, obj: any, prettyPrint: boolean): void;
Formats and writes a marking log message.
This is best used to describe events that need to stand out in the log.
Some examples of mark
messages:
`Entering method ${ methodName } at ${ timestamp }`
`Exiting method ${ methodName } at ${ timestamp }`
(go to top)
LogManager
LogManager: The default StatusLog manager.
Any ILogManager
exposes the following members:
(go to top)
initialize
A
LogBuilder
that configures a logger.
LogManager.initialize
is meant to be a fluent interface, and exposes the following members:
Example:
const consoleLog = LogManager.initialize
.newLog('console log')
.newChannel('console channel', CONSOLE, LogLevel.INFO)
.andGetLogger();
consoleLog.mark('Logger configured.');
For more details, see the ILogBuilder abstraction.
(go to top)
disable
LogManager.disable(logName: string): void;
Disables the log with the given name.
(go to top)
enable
LogManager.enable(logName: string): void;
Enables the log with the given name.
(go to top)
getLog
LogManager.getLog(logName: string): ILog | null;
Returns the ILog
instance with the given name.
Returns null
if not found.
(go to top)
Loggers
ConsoleLog: The default console logger.
TerminalLog: The default terminal logger.
Both ConsoleLog
and TerminalLog
are instances of the IStatusLog
abstraction.
TerminalLog
TerminalLog
is the default logger the terminal (e.g., for use in node applications). It has a single channel, called 'terminal', utilizing a TerminalWriter
, and configured at LogLevel.INFO
.
ConsoleLog
ConsoleLog
is the default logger for the browser console.
It has a single channel, called 'console', utilizing a ConsoleWriter
, and also configured at LogLevel.INFO
.
(go to top)
Writers
CONSOLE: The default console writer.
TERMINAL: The default terminal writer.
Both CONSOLE
and TERMINAL
are instances of the IWriter
abstraction.
TERMINAL
TERMINAL
is the default writer for the terminal (e.g., for use in node applications).
CONSOLE
CONSOLE
is the default writer for the browser console.
(go to top)
Tables
Date Formatting
Date formatting is based on Unicode Technical Standard #35.
Specifically, it depends on the date-fns and date-fns-tz libraries to do most of the date formatting.
Date token format: { %date [
|<format string>[
| <timezone> ] ] }
example timestamp: 2021-04-25 19:00:43.426 GMT-7 (America/Los Angeles)
| Date Format | desired result | date token |
|:---|:---|:---|
| Default | 2021-04-25 19:00:43.426 -07:00
| %{ date }
|
| "long" format | 2021-04-26 19:00:43 -0700
| %{ date \| yyyy-MM-dd HH:mm:ss XXXX }
|
| ISO-8601 (UTC) | 2021-04-26T02:00:43.426Z
| %{ date \| yyyy-MM-dd'T'HH:mm:ss.SSS'Z' \| UTC }
|
| UTC format | Mon, 26 Apr 2021 02:00:43 UTC
| %{ date \| EEE',' dd MMM yyyy HH:mm:ss xxx \| UTC }
|
(go to top)
Logging Writers
We need to enable logging to many possible targets, for example:
| Example Target | Description |
|:---|:---|
|CONSOLE
| The browser console |
|TERMINAL
| The terminal (non-browser) |
(go to top)
Log Levels
|Log Level |Importance| |:---|:---| |Fatal |One or more key business functionalities are not working and the whole system doesn’t fulfill the business functionalities.| |Error |One or more functionalities are not working, preventing some functionalities from working correctly.| |Warn |Unexpected behavior happened inside the application, but it is continuing its work and the key business features are operating as expected.| |Info |An event happened, the event is purely informative and can be ignored during normal operations.| |Debug |Useful during software debugging when more granular information is needed.| |Trace |Step by step execution of your code that can be ignored during the standard operation, but may be useful during extended debugging sessions.|
(go to top)
Entry Statuses
| Status |Importance| |:---|:---| | failure | Non-code failure (login failure, etc.) | | info | Informational | | mark | Code-execution condition, timestamp, or metrics. | | success | Successful completion of an operation. |
(go to top)
Log Entry Fields
|Log Entry Property |Importance| |:---|:---| |data | Any accompanying data that should be included and logged. | |level | The level at which to log the message. | |message | The message to log. | |source | The source of the log entry. | |timestamp | The date and time of the entry. |
(go to top)
Caveats
- @auturge/logger does not (currently) include functionality that makes it a file or database logger, but an interested party might create such an
IWriter
, and I might be happy to review and include it.
(go to top)
License
Distributed under the MIT license. See LICENSE
for more information.
(go to top)