Logging

Overview

@marblejs/core defines a pluggable Logger dependency registered by default to the context of every server factory. Having that you can inspect things like, registered context dependencies, mapped HTTP routes, request/response logs, I/O event traces, etc.

Logger

The interface allows you to define the log tag, type, main message and an optional level, which if not defined defaults to LoggerLevel.INFO.
1
{
2
tag: 'event_bus',
3
type: 'saveOfferDocument#x27;,
4
message: 'Saving offer document...',
5
level: LoggerLevel.INFO
6
}
Copied!
1
enum LoggerLevel { INFO, WARN, ERROR, DEBUG, VERBOSE };
2
3
interface LoggerOptions = {
4
tag: string;
5
type: string;
6
message: string;
7
level?: LoggerLevel;
8
};
Copied!
Marble.js logger is an instance of IO monad which represents a synchronous effectful computation. In order to execute the logger you have to "run the IO action".
1
Logger :: LoggerOptions -> IO<void>;
Copied!
1
import { LoggerTag, LoggerToken, LoggerLevel, useContext } from '@marblejs/core';
2
import { r } from '@marblejs/http';
3
import { requestValidator$, t } from '@marblejs/middleware-io';
4
import { tap } from 'rxjs/operators';
5
import { UserDto } from './user.dto';
6
7
const foo$ = r.pipe(
8
r.matchPath('/foo'),
9
r.matchType('GET'),
10
r.useEffect((req$, ctx) => {
11
const logger = useContext(LoggerToken)(ctx.ask);
12
13
const logMagic = logger({
14
tag: LoggerTag.HTTP
15
level: LoggerLevel.INFO,
16
type: 'foo#x27;,
17
message: 'Here the magic happens...',
18
});
19
20
return req$.pipe(
21
tap(logMagic),
22
// ..
23
));
24
});
Copied!

Custom logger

You can override the binding and map the stdout IO operations to a different destination (e.g. file or external service) when needed.
logger.reader.ts
1
import * as O from 'fp-ts/lib/Option';
2
import { pipe } from 'fp-ts/lib/function';
3
import { Logger, LoggerLevel, createReader } from '@marblejs/core';
4
import { CustomLogger } from './customLogger';
5
6
export const CustomLoggerReader = createReader<Logger>(() => opts => {
7
const tag = opts.tag;
8
const level = opts.level ?? LoggerLevel.INFO;
9
const message = `${opts.type} ${opts.message}`;
10
const log = pipe(
11
O.fromNullable({
12
[LoggerLevel.ERROR]: CustomLogger.error,
13
[LoggerLevel.INFO]: CustomLogger.log,
14
[LoggerLevel.WARN]: CustomLogger.warn,
15
}[level),
16
O.getOrElse(() => CustomLogger.log),
17
);
18
19
return () => log({ tag, message });
20
});
Copied!
Then in your server definition you have to override the binding.
1
import { bindTo, LoggerToken } from '@marblejs/core';
2
import { createServer } from '@marblejs/http';
3
import { CustomeLoggerReader } from './logger.reader.ts';
4
5
const server = createServer({
6
// ...
7
dependencies: [
8
bindTo(LoggerToken)(CustomLoggerReader),
9
],
10
});
Copied!
Last modified 1mo ago