Skip to content

Commit

Permalink
feat: add support for json log formats (#3783)
Browse files Browse the repository at this point in the history
Co-authored-by: nabeelsaabna <[email protected]>
  • Loading branch information
nabeelsaabna and nabeelsaabna authored Dec 11, 2024
1 parent 1f4463d commit 2bf3b88
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
38 changes: 38 additions & 0 deletions src/cli/utils/logger.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ describe('cli/utils/logger', () => {
beforeEach(() => {
vi.resetModules();
delete env.CONTAINERBASE_LOG_LEVEL;
delete env.CONTAINERBASE_LOG_FORMAT;
delete env.LOG_LEVEL;
delete env.LOG_FORMAT;
delete env.CONTAINERBASE_LOG_FILE;
delete env.CONTAINERBASE_LOG_FILE_LEVEL;
delete env.CONTAINERBASE_DEBUG;
Expand All @@ -32,4 +35,39 @@ describe('cli/utils/logger', () => {
},
);
});

test('works - stdout with json', async () => {
env.CONTAINERBASE_LOG_FORMAT = 'json';
const { pino } = await import('pino');
const mod = await import('./logger');
expect(mod.logger).toBeDefined();
expect(pino).toHaveBeenCalledWith(
{ level: 'info' },
{
targets: [{ target: 'pino/file', level: 'info', options: {} }],
},
);
});

test('works - debug stdout with json with file', async () => {
env.LOG_FORMAT = 'json';
env.CONTAINERBASE_LOG_LEVEL = 'warn';
env.CONTAINERBASE_LOG_FILE = 'test.ndjson';
const { pino } = await import('pino');
const mod = await import('./logger');
expect(mod.logger).toBeDefined();
expect(pino).toHaveBeenCalledWith(
{ level: 'debug' },
{
targets: [
{ target: 'pino/file', level: 'warn', options: {} },
{
target: 'pino/file',
level: 'debug',
options: { destination: 'test.ndjson' },
},
],
},
);
});
});
10 changes: 9 additions & 1 deletion src/cli/utils/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,18 @@ const level =
.filter(isNonEmptyStringAndNotWhitespace)
.shift() ?? 'info';

const format =
[env.CONTAINERBASE_LOG_FORMAT, env.LOG_FORMAT]
.filter(isNonEmptyStringAndNotWhitespace)
.shift()
?.toLowerCase() ?? 'pretty';

const stdoutTransportTarget = format === 'json' ? 'pino/file' : 'pino-pretty';

let fileLevel = 'silent';

const targets: TransportTargetOptions[] = [
{ target: 'pino-pretty', level, options: {} },
{ target: stdoutTransportTarget, level, options: {} },
];

if (isNonEmptyStringAndNotWhitespace(env.CONTAINERBASE_LOG_FILE)) {
Expand Down

0 comments on commit 2bf3b88

Please sign in to comment.