Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(sdk-logs): added colors option to ConsoleLogRecordExporter #4524

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions experimental/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ All notable changes to experimental packages in this project will be documented

### :rocket: (Enhancement)

* feat(sdk-logs): added colors option to ConsoleLogRecordExporter
* refactor(instr-http): use exported strings for semconv. [#4573](https://github.com/open-telemetry/opentelemetry-js/pull/4573/) @JamieDanielson
* feat(sdk-node): add `HostDetector` as default resource detector

Expand Down
2 changes: 2 additions & 0 deletions experimental/packages/sdk-logs/karma.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ module.exports = config => {
config.set(
Object.assign({}, karmaBaseConfig, {
webpack: karmaWebpackConfig,
files: ['test/browser/index-webpack.ts'],
preprocessors: { 'test/browser/index-webpack.ts': ['webpack'] },
})
);
};
1 change: 1 addition & 0 deletions experimental/packages/sdk-logs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
"@types/mocha": "10.0.6",
"@types/node": "18.6.5",
"@types/sinon": "10.0.20",
"ansi-regex": "^5.0.1",
"babel-plugin-istanbul": "6.1.1",
"codecov": "3.8.3",
"cross-var": "1.1.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import { ExportResult, hrTimeToMicroseconds } from '@opentelemetry/core';
import { ExportResultCode } from '@opentelemetry/core';

import type { ConsoleLogRecordExporterConfig } from '../types';
import type { ReadableLogRecord } from './ReadableLogRecord';
import type { LogRecordExporter } from './LogRecordExporter';

Expand All @@ -27,6 +28,15 @@ import type { LogRecordExporter } from './LogRecordExporter';

/* eslint-disable no-console */
export class ConsoleLogRecordExporter implements LogRecordExporter {
private _dirOpts: {
depth: number;
colors?: boolean;
} = { depth: 3 };

constructor(config: ConsoleLogRecordExporterConfig = {}) {
if (typeof config.colors !== 'undefined')
this._dirOpts.colors = config.colors;
}
/**
* Export logs.
* @param logs
Expand Down Expand Up @@ -73,7 +83,7 @@ export class ConsoleLogRecordExporter implements LogRecordExporter {
done?: (result: ExportResult) => void
): void {
for (const logRecord of logRecords) {
console.dir(this._exportInfo(logRecord), { depth: 3 });
console.dir(this._exportInfo(logRecord), this._dirOpts);
}
done?.({ code: ExportResultCode.SUCCESS });
}
Expand Down
1 change: 1 addition & 0 deletions experimental/packages/sdk-logs/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export {
LogRecordLimits,
BufferConfig,
BatchLogRecordProcessorBrowserConfig,
ConsoleLogRecordExporterConfig,
} from './types';
export { LoggerProvider } from './LoggerProvider';
export { LogRecord } from './LogRecord';
Expand Down
5 changes: 5 additions & 0 deletions experimental/packages/sdk-logs/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,8 @@ export interface BatchLogRecordProcessorBrowserConfig extends BufferConfig {
* on mobile, switches to a different app. Auto flush is enabled by default. */
disableAutoFlushOnDocumentHide?: boolean;
}

export interface ConsoleLogRecordExporterConfig {
/** Force colorization of console logs instead of relying on detection */
colors?: boolean;
}
23 changes: 23 additions & 0 deletions experimental/packages/sdk-logs/test/browser/index-webpack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const testsContext = require.context('../browser', true, /test$/);
testsContext.keys().forEach(testsContext);

const testsContextCommon = require.context('../common', true, /test$/);
testsContextCommon.keys().forEach(testsContextCommon);

const srcContext = require.context('.', true, /src$/);
srcContext.keys().forEach(srcContext);
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,11 @@ import {

/* eslint-disable no-console */
describe('ConsoleLogRecordExporter', () => {
let previousConsoleDir: typeof console.dir;

beforeEach(() => {
previousConsoleDir = console.dir;
console.dir = () => {};
});

afterEach(() => {
console.dir = previousConsoleDir;
});

describe('export', () => {
it('should export information about log record', () => {
assert.doesNotThrow(() => {
const consoleExporter = new ConsoleLogRecordExporter();
const spyConsole = sinon.spy(console, 'dir');
const spyConsole = sinon.stub(console, 'dir');
const spyExport = sinon.spy(consoleExporter, 'export');
const provider = new LoggerProvider();
provider.addLogRecordProcessor(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import * as assert from 'assert';
import * as sinon from 'sinon';
import * as ansiRegex from 'ansi-regex';
import { SeverityNumber } from '@opentelemetry/api-logs';

import {
LoggerProvider,
ConsoleLogRecordExporter,
SimpleLogRecordProcessor,
} from './../../../src';

const isColorText = (text: string) => ansiRegex().test(text);

describe('ConsoleLogRecordExporter', () => {
describe('config', () => {
it('should not set the colors option by default', () => {
const consoleExporter = new ConsoleLogRecordExporter();
const consoleSpy = sinon.spy(console, 'dir');
const provider = new LoggerProvider();
provider.addLogRecordProcessor(
new SimpleLogRecordProcessor(consoleExporter)
);

const stdoutStub = sinon.stub(process.stdout, 'write');
provider.getLogger('default').emit({
body: 'body1',
severityNumber: SeverityNumber.DEBUG,
severityText: 'DEBUG',
});
stdoutStub.restore();
const consoleDirOpts = consoleSpy.args[0][1];
consoleSpy.restore();

assert.equal(consoleDirOpts?.colors, undefined);
});

it('should colorize log records when options.colors is true', () => {
const consoleExporter = new ConsoleLogRecordExporter({ colors: true });
const provider = new LoggerProvider();
provider.addLogRecordProcessor(
new SimpleLogRecordProcessor(consoleExporter)
);

const consoleSpy = sinon.spy(console, 'dir');
const stdoutStub = sinon.stub(process.stdout, 'write');
provider.getLogger('default').emit({
body: 'body2',
severityNumber: SeverityNumber.DEBUG,
severityText: 'DEBUG',
});
const consoleOutput = stdoutStub.getCalls()[0].firstArg;
const consoleDirOpts = consoleSpy.args[0][1];
stdoutStub.restore();
consoleSpy.restore();

assert.equal(consoleDirOpts?.colors, true);
const containsColor = isColorText(consoleOutput);
assert.ok(containsColor);
});

it('should not colorize log records when options.colors is false', () => {
const consoleExporter = new ConsoleLogRecordExporter({ colors: false });
const provider = new LoggerProvider();
provider.addLogRecordProcessor(
new SimpleLogRecordProcessor(consoleExporter)
);

const consoleSpy = sinon.spy(console, 'dir');
const stdoutStub = sinon.stub(process.stdout, 'write');
provider.getLogger('default').emit({
body: 'body3',
severityNumber: SeverityNumber.DEBUG,
severityText: 'DEBUG',
});
const consoleOutput = stdoutStub.getCalls()[0].firstArg;
const consoleDirOpts = consoleSpy.args[0][1];
stdoutStub.restore();
consoleSpy.restore();

assert.equal(consoleDirOpts?.colors, false);
const doesNotContainColor = !isColorText(consoleOutput);
assert.ok(doesNotContainColor);
});
});
});
9 changes: 7 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.