Package Exports
- tslog
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (tslog) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
📝 tslog: Brand new expressive TypeScript Logger for Node.js
Powerful, fast and expressive logging for Node.js

Highlights
⚡ Small footprint, blazing performance
👮️ Fully typed with TypeScript support (exact code position)
🗃 Pretty or JSON output
🦸 Custom pluggable loggers
💅 Object and error interpolation
🕵️ Code surrounding error position (code frame)
🤓 Stack trace through native V8 API
🏗 Works for TypeScript and JavaScript
🧲 Optionally catch all console logs
✍️ well documented
😎 100% test coverage
Example
import { Logger } from "tslog";
const log: Logger = new Logger();
log.silly("I am a silly log.");Install
npm install tslogEnable TypeScript source map support:
This feature enables tslog to reference a correct line number in your TypeScript source code.
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"sourceMap": true
}
}Simple usage
import { Logger } from "tslog";
const log: Logger = new Logger({ name: "myLogger" });
log.silly("I am a silly log.");
log.trace("I am a trace log with a stack trace.");
log.debug("I am a debug log.");
log.info("I am an info log.");
log.warn("I am a warn log with a json object:", {foo: "bar"});
log.error("I am an error log.");
log.fatal(new Error("I am a pretty Error with a stacktrace."));All Features
- Log level:
silly,trace,debug,info,warn,error,fatal(different colors) - Output to std: Structured/pretty output (easy parsable
tabdelimiters),JSONor suppressed - Attachable transports: Send logs to an external log aggregation services, file system, database, or email/slack/sms/you name it...
- Correct std per log level: stdout for
silly,trace,debug,infoand stderr forwarn,error,fatal - Minimum log level per output:
minLevellevel can be set individually per transport - Fully typed: Written in TypeScript, fully typed, API checked with api-extractor, TSDoc documented
- Source maps lookup: Shows exact position also in TypeScript code (compile-to-JS), one click to IDE position.
- Stack trace: Callsites through native V8 stack trace API, excludes internal entries
- Pretty Error: Errors and stack traces printed in a structured way and fully accessible through JSON (e.g. external Log services)
- Code frame:
tslogcaptures and displays the source code that lead to an error, making it easier to debug - Object/JSON highlighting: Nicely prints out an object
- Instance Name: Logs capture instance name (default host name) making it easy to distinguish logs coming from different instances (e.g. serverless)
- Named Logger: Logger can be named (e.g. useful for packages/modules and monorepos)
- Highly configurable: All settings can be changed through a typed object
- Short paths: Paths are relative to the root of the application folder
- Runtime-agnostic: Works with
ts-node,ts-node-dev, as well as compiled down to JavaScript - Optionally overwrite
console: Catchconsole.logetc. that would otherwise be hard to find - Tested: 100% code coverage, CI
API documentation
📘 TSDoc
Log level
tslog is highly customizable, however, it follows convention over configuration when it comes to log levels.
Internally a log level is represented by a numeric ID.
Supported log levels are:
0: silly, 1: trace, 2: debug, 3: info, 4: warn, 5: error, 6: fatal
Per default log level 0 - 3 are written to stdout and 4 - 6 are written to stderr.
Each log level is printed in a different color, that is completely customizable through the settings object.
Hint: Log level
tracebehaves a bit differently compared to all the other log levels. While it is possible to activate a stack trace for every log level, it is already activated fortraceby default. That means everytracelog will also automatically capture and print its entire stack trace.
import { Logger } from "tslog";
const log: Logger = new Logger();
log.silly("I am a silly log.");
log.trace("I am a trace log with a stack trace.");
log.debug("I am a debug log.");
log.info("I am an info log.");
log.warn("I am a warn log with a json object:", {foo: "bar"});
log.error("I am an error log.");
log.fatal(new Error("I am a pretty Error with a stacktrace."));Structured (aka. pretty) log level output would look like this:

Hint: Each logging method has a return type, which is a JSON representation of the log message (
ILogObject). You can use this object to access its stack trace etc.
import { Logger, ILogObject } from "tslog";
const log: Logger = new Logger();
const logWithTrace: ILogObject = log.trace("I am a trace log with a stack trace.");
console.log(JSON.stringify(logWithTrace, null, 2));Settings
As tslog follows the convention over configuration approach, it already comes with reasonable default settings.
Nevertheless, it can be flexibly adapted to your own needs.
All possible settings are defined in the ISettingsParam interface and modern IDE will offer autocompletion accordingly.
And of course, all of them are optional and can also be combined with your needs.
instanceName
default: os.hostname (hidden by default)
You can provide each logger with the name of the instance, making it easy to distinguish logs from different machines.
This approach works well in the serverless environment as well, allowing you to filter all logs coming from a certain instance.
Per default instanceName is pre-filled with the hostname of your environment, which can be overwritten.
However, this value is hidden by default in order to keep the log clean and tidy.
You can change this behavior by setting displayInstanceName to true.
const logger: Logger = new Logger({ displayInstanceName: true });
// Would print out the host name of your machine
const logger: Logger = new Logger({ displayInstanceName: true, instanceName: "ABC" });
// Would print out ABC as the name of this instance
name
default: ""
Each logger has an optional name, that is hidden by default.
This setting is particularly interesting when working in a monorepo,
giving you the chance to provide each module/package with its own logger and being able to distinguish logs coming from different parts of your application.
new Logger({ name: "myLogger" });minLevel
default: "silly"
What should be the minimum log level that should be captured by this logger?
Possible values are: silly, trace, debug, info, warn, error, fatal
logAsJson
default: false
Sometimes you want to forward your logs directly from your std to another log service.
Instead of parsing the pretty output, most log services can easily parse a JSON object.
This gives you direct access to all the information captured by
tslog, like stack trace and code frame information.
new Logger({ logAsJson: true });Resulting in the following output:

Hint: Each JSON log is printed in one line, making it easily parsable by external services.
exposeStack
default: false
Usually, only Errors and log level trace logs would capture the entire stack trace.
By enabling this option every stack trace of every log message is going to be captured.
new Logger({ exposeStack: true });
Hint: When working in an IDE like WebStorm or an editor like VSCode you can click on the path leading you directly to the position in your source code.
exposeErrorCodeFrame
default: true
A nice feature of tslog is to capture the code frame around the error caught, showing the exact location of the error.
While it comes quite handy during development, it also means that the source file (*.js or *.ts) needs to be loaded.
When running in production, you probably want as much performance as possible and since errors are analyzed at a later point in time,
you may want to disable this feature.
new Logger({ exposeErrorCodeFrame: false });Hint: By default 5 lines before and after the line with the error will be displayed.
You can adjust this setting withexposeErrorCodeFrameLinesBeforeAndAfter.

suppressStdOutput
default: false
It is possible to connect multiple transports (external loggers) to tslog (see below).
In this case it might be useful to suppress all output.
new Logger({ suppressStdOutput: true });overwriteConsole
default: false
tslog is designed to be used directly through its API.
However, there might be use cases, where you want to make sure to capture all logs,
even though they might occur in a library or somebody else's code.
Or maybe you prefer or used to work with console, like console.log, console.warn and so on.
In this case, you can advise tslog to overwrite the default behavior of console.
Hint: It is only possible to overwrite
consoleonce, so the last attempt wins. If you wish to do so, I would recommend to have a designated logger for this purpose.
new Logger({ name: "console", overwriteConsole: true });tslog applies the following mapping:
console.log:sillyconsole.trace:traceconsole.info:infoconsole.warn:warnconsole.error:error
There is no console.fatal.
logLevelsColors
This setting allows you to overwrite the default log level colors of tslog.
jsonHighlightColors
This setting allows you to overwrite the default colors of JSON interpolation.
stdOut and stdErr
This both settings allow you to replace the default stdOut and stdErr WriteStreams.
However, this would lead to a colorized output. We use this setting mostly for testing purposes.
If you want to redirect the output or directly access any logged object, we advise you to attach a transport (see below).
Transports
tslog focuses on the one thing it does well: capturing logs.
Therefor there is no build-in file system logging, log rotation, or similar.
Per default all logs go to stdOut and stdErr respectively.
However, you can easily attach as many transports as you wish, enabling you to do fancy stuff like sending a message to Slack or Telegram in case of an urgent error.
When attaching a transport, you must implement every log level. All of them could be potentially handled by the same function, though.
Each transport can have its own minLevel.
Simple transport example
Here is a very simple implementation used in our jest tests:
import { ILogObject, Logger } from "tslog";
const transportLogs: ILogObject[] = [];
function logToTransport(logObject: ILogObject) {
transportLogs.push(logObject);
}
const logger: Logger = new Logger();
logger.attachTransport(
{
silly: logToTransport,
debug: logToTransport,
trace: logToTransport,
info: logToTransport,
warn: logToTransport,
error: logToTransport,
fatal: logToTransport,
},
"debug"
);Storing logs in a file
Here is an example how to store all logs in a file.
import { ILogObject, Logger } from "tslog";
import { appendFileSync } from "fs";
function logToTransport(logObject: ILogObject) {
appendFileSync("logs.txt", JSON.stringify(logObject) + "\n");
}
const logger: Logger = new Logger();
logger.attachTransport(
{
silly: logToTransport,
debug: logToTransport,
trace: logToTransport,
info: logToTransport,
warn: logToTransport,
error: logToTransport,
fatal: logToTransport,
},
"debug"
);
log.debug("I am a debug log.");
log.info("I am an info log.");
log.warn("I am a warn log with a json object:", { foo: "bar" });Result: logs.txt
{"loggerName":"","date":"2020-04-27T15:24:04.334Z","logLevel":"debug","logLevelId":2,"filePath":"example/index.ts","fullFilePath":"/Users/eugene/Development/workspace/tslog/example/index.ts","fileName":"index.ts","lineNumber":56,"columnNumber":5,"isConstructor":false,"functionName":null,"typeName":"Object","methodName":null,"argumentsArray":["I am a debug log."]}
{"loggerName":"","date":"2020-04-27T15:24:04.334Z","logLevel":"info","logLevelId":3,"filePath":"example/index.ts","fullFilePath":"/Users/eugene/Development/workspace/tslog/example/index.ts","fileName":"index.ts","lineNumber":57,"columnNumber":5,"isConstructor":false,"functionName":null,"typeName":"Object","methodName":null,"argumentsArray":["I am an info log."]}
{"loggerName":"","date":"2020-04-27T15:24:04.335Z","logLevel":"warn","logLevelId":4,"filePath":"example/index.ts","fullFilePath":"/Users/eugene/Development/workspace/tslog/example/index.ts","fileName":"index.ts","lineNumber":58,"columnNumber":5,"isConstructor":false,"functionName":null,"typeName":"Object","methodName":null,"argumentsArray":["I am a warn log with a json object:",{"foo":"bar"}]}