ag-logger-npm
v2.0.0
Published
the ult logger
Downloads
2
Readme
Description
Package creation is based on the tutorial described in the tutorial
section.
"version: 1.0.2" of this logger was completly build by chatGPT
including the README it self :)
The questions for GPT were:
write a typescript logger with several levels that accept message and additional objects and support console and json formatters options and show how to test it
show how to test this with jest
create a readme file for this project
add color to the console formater
add correlation id using context
AG TypeScript Logger
A TypeScript logger with several levels that accepts messages and additional objects, supports console and JSON formatters, and is tested with Jest.
Installation
To install the logger, run the following command:
@ npm install --save ag-logger-npm
Usage
To use the logger in your TypeScript project, import the AGLogger class from the package and create a new instance with the desired log level and options:
import { AGLogger, LogLevel, LogFormat } from 'ag-looger-npm'
const logger = new AGLogger(LogLevel.DEBUG, { logFormat: LogFormat.console });
You can then use the logger's methods (error, warn, info, debug) to log messages and additional objects:
const consoleLogger = new AGLogger(LogLevel.DEBUG, { logFormat: LogFormat.console });
consoleLogger.error('An error occurred!', { errorCode: 123 }, { foo: "moo "});
consoleLogger.warn('A warning!', [1, 2, 3]);
consoleLogger.info('An information message', { user: { id: 123, name: 'John' }});
consoleLogger.trace("This is a trace message"); // output: [TRACE] This is a trace message
consoleLogger.debug('A debug message', 'debugging...');
You can also configure the logger to log messages in JSON format:
const jsonLogger = new AGLogger(LogLevel.DEBUG, { logFormat: LogFormat.json });
jsonLogger.error('An error occurred!', { errorCode: 123 }, { foo: "moo "});
jsonLogger.warn('A warning!', [1, 2, 3]);
jsonLogger.info('An information message', { user: { id: 123, name: 'John' }});
jsonLogger.debug('A debug message', 'debugging...');
jsonLogger.error("An error occurred!", { errorCode: 123 });
and to carry correlation id:
import { AGCorrelatedLogger, CorrelationContext, LogLevel, LogFormat } from 'ag-looger-npm'
CorrelationContext.setCorrelationId("abcd-1234");
const correlatedConsoleLogger = new AGCorrelatedLogger(LogLevel.DEBUG, { logFormat: LogFormat.console });
correlatedConsoleLogger.info("Hello, world!");
correlatedConsoleLogger.error('An error occurred!', { errorCode: 123 }, { foo: "moo "});
correlatedConsoleLogger.warn('A warning!', [1, 2, 3]);
correlatedConsoleLogger.info('An information message', { user: { id: 123, name: 'John' }});
correlatedConsoleLogger.debug('A debug message', 'debugging...');
correlatedConsoleLogger.error("An error occurred!", { errorCode: 123 });
The results:
[ERROR] An error occurred! {"errorCode":123} {"foo":"moo "}
[WARN] A warning! [1,2,3]
[INFO] An information message {"user":{"id":123,"name":"John"}}
[TRACE] This is a trace message
[DEBUG] A debug message debugging...
{"level":0,"levelString":"ERROR","message":"An error occurred!","args":[{"errorCode":123},{"foo":"moo "}]}
{"level":1,"levelString":"WARN","message":"A warning!","args":[[1,2,3]]}
{"level":3,"levelString":"INFO","message":"An information message","args":[{"user":{"id":123,"name":"John"}}]}
{"level":4,"levelString":"DEBUG","message":"A debug message","args":["debugging..."]}
{"level":0,"levelString":"ERROR","message":"An error occurred!","args":[{"errorCode":123}]}
[INFO] [abcd-1234] Hello, world!
[ERROR] [abcd-1234] An error occurred! {"errorCode":123} {"foo":"moo "}
[WARN] [abcd-1234] A warning! [1,2,3]
[INFO] [abcd-1234] An information message {"user":{"id":123,"name":"John"}}
[DEBUG] [abcd-1234] A debug message debugging...
[ERROR] [abcd-1234] An error occurred! {"errorCode":123}
{"level":3,"levelString":"INFO","correlationId":"efg-7890","message":"Hello, world!","args":[]}
{"level":0,"levelString":"ERROR","correlationId":"efg-7890","message":"An error occurred!","args":[{"errorCode":123},{"foo":"moo "}]}
{"level":1,"levelString":"WARN","correlationId":"efg-7890","message":"A warning!","args":[[1,2,3]]}
{"level":3,"levelString":"INFO","correlationId":"efg-7890","message":"An information message","args":[{"user":{"id":123,"name":"John"}}]}
{"level":4,"levelString":"DEBUG","correlationId":"efg-7890","message":"A debug message","args":["debugging..."]}
{"level":0,"levelString":"ERROR","correlationId":"efg-7890","message":"An error occurred!","args":[{"errorCode":123}]}
Options
The AGLogger
class accepts an options object with the following properties:
LogFormat.console
(default) - Whether to format messages for the console output.LogFormat.json
- Whether to format messages as JSON strings.
Log Levels
The LogLevel
enum contains the following log levels, in order of increasing severity:
- ERROR
- WARN
- INFO
- TRACE
- DEBUG (default)
By default, the logger logs all messages with a log level equal to or above the log level set when creating the logger.
internal Testing
To test the logger using Jest, create test files with the .test.ts or .spec.ts extension, and run them using the npm test
(or: yarn test
) command.
Here's an example of how to test the logger:
import { AGLogger, LogLevel } from 'ag-looger-npm';
const consoleLogger = new AGLogger(LogLevel.DEBUG, { logFormat: LogFormat.console });
describe('Logger', () => {
let logger: Logger;
beforeEach(() => {
logger = new AGLogger(LogLevel.DEBUG, { logFormat: LogFormat.console })
it('should log an error message with arguments', () => {
logger.error('An error occurred!', { errorCode: 123 });
// Assert that the error message was logged to the console
expect(console.log).toHaveBeenCalledWith(
expect.stringContaining('[ERROR] An error occurred! {"errorCode":123}')
);
});
// More test cases...
});
Building a package
tutorial
https://www.youtube.com/watch?v=Nh9xW2-ZOEU&t=639s
init package.json:
$ npm init -y
//add this to config:
"main": "dist/index.js",
"types": "dist/index.d.js",
"files": ['/dist'],
install typescript:
$ npm install typescript
$ npx tsc --init #init the tsconfig.json with ALL the compiler options
clear and create this configuration:
{
"compilerOptions": {
"module": "Commonjs",
"target": "es2015",
"sourceMap": true,
"outDir": "./dist",
"noImplicitAny": true,
"declaration": true,
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
Compile TS:
$ npx tsc
NPM stuff
`$ npm login`
'$ npm publish'
tester
To test typescript directly without compilng usei install ts-node: https://www.npmjs.com/package/ts-node
ts-node src/main
Some Git commands
$ git commit -m "first commit" #will require specifying files
$ git commit -m "add few stuff" --all
$ git push -u origin main
$ git add -A #stage all files
test the package form external folder
without publishing
$ npm link ../ag-logger-npm
License
This project is licensed under the MIT License - see the LICENSE file for details.