Skip to content

Commit

Permalink
[FEATURE] Pouvoir logger en debug sur un scope réduit (PIX-15534)
Browse files Browse the repository at this point in the history
  • Loading branch information
pix-service-auto-merge authored Dec 4, 2024
2 parents 1094427 + eadc7db commit e025664
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
9 changes: 9 additions & 0 deletions api/sample.env
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,15 @@ LOG_FOR_HUMANS=true
# LOG_FOR_HUMANS_FORMAT=compact


# Enables debug log level for a list of sections.
# Sections must be given separated by commas.
# micromatch syntax may be used to match several sections.
# presence: optional
# type: string
# default: none
# LOG_DEBUG=learningcontent:*,foo,bar


# Trace email sending in the mailer
# DEBUG="pix:mailer:email"

Expand Down
1 change: 1 addition & 0 deletions api/src/shared/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@ const configuration = (function () {
enableLogStartingEventDispatch: toBoolean(process.env.LOG_STARTING_EVENT_DISPATCH),
enableLogEndingEventDispatch: toBoolean(process.env.LOG_ENDING_EVENT_DISPATCH),
opsEventIntervalInSeconds: process.env.OPS_EVENT_INTERVAL_IN_SECONDS || 15,
debugSections: process.env.LOG_DEBUG?.split(',') ?? [],
},
login: {
temporaryBlockingThresholdFailureCount: _getNumber(
Expand Down
21 changes: 18 additions & 3 deletions api/src/shared/infrastructure/utils/logger.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import isEmpty from 'lodash/isEmpty.js';
import omit from 'lodash/omit.js';
import micromatch from 'micromatch';
import pino from 'pino';
import pretty from 'pino-pretty';

Expand All @@ -20,7 +21,7 @@ if (logging.logForHumans) {
});
}

const logger = pino(
export const logger = pino(
{
level: logging.logLevel,
redact: ['req.headers.authorization'],
Expand All @@ -29,6 +30,22 @@ const logger = pino(
prettyPrint,
);

/**
* Creates a child logger for a section.
* Debug may be enabled for a section using LOG_DEBUG.
* @param {string} section
* @param {pino.Bindings} bindings
* @param {pino.ChildLoggerOptions} options
*/
export function child(section, bindings, options) {
/** @type{Partial<pino.ChildLoggerOptions>} */
const optionsOverride = {};
if (micromatch.isMatch(section, logging.debugSections)) {
optionsOverride.level = 'debug';
}
return logger.child(bindings, { ...options, ...optionsOverride });
}

function messageFormatCompact(log, messageKey, _logLevel, { colors }) {
const message = log[messageKey];
const { err, req, res, responseTime } = log;
Expand Down Expand Up @@ -71,5 +88,3 @@ function messageFormatCompact(log, messageKey, _logLevel, { colors }) {
const details = !isEmpty(compactLog) ? colors.gray(JSON.stringify(compactLog)) : '';
return `${message} ${details}`;
}

export { logger };

0 comments on commit e025664

Please sign in to comment.