Skip to content

Commit

Permalink
fix: log to console using structured logging (#780)
Browse files Browse the repository at this point in the history
Replaces 'console-log-level' with '@google-cloud/logging-min' to write logs to stdout.
Replaces new line with its escape notation '\\n'.
Refactors single location that prints array to print a single string.
  • Loading branch information
minherz authored Dec 20, 2021
1 parent ac83b29 commit 6b96e00
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 27 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"license": "Apache-2.0",
"dependencies": {
"@google-cloud/common": "^3.0.0",
"@google-cloud/logging-min": "^9.6.3",
"@types/console-log-level": "^1.4.0",
"@types/semver": "^7.0.0",
"console-log-level": "^1.4.0",
Expand Down
7 changes: 4 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ export async function startLocal(config: Config = {}): Promise<void> {
setInterval(() => {
const curTime = Date.now();
const {rss, heapTotal, heapUsed} = process.memoryUsage();
logger.debug(
const debugInfo = [
new Date().toISOString(),
'rss',
(rss / (1024 * 1024)).toFixed(3),
Expand All @@ -252,8 +252,9 @@ export async function startLocal(config: Config = {}): Promise<void> {
'profiles/s,',
'time profile collection rate',
((timeProfileCount * 1000) / (curTime - prevLogTime)).toFixed(3),
'profiles/s'
);
'profiles/s',
].map(v => v + '');
logger.debug(debugInfo.join(' '));

heapProfileCount = 0;
timeProfileCount = 0;
Expand Down
86 changes: 62 additions & 24 deletions src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,36 +12,74 @@
// See the License for the specific language governing permissions and
// limitations under the License.

import * as consoleLogLevel from 'console-log-level';
/* eslint-disable @typescript-eslint/no-explicit-any */

import {defaultConfig} from './config';
import {LogSync, Logging} from '@google-cloud/logging-min';

const logging = new Logging();

// migrating from 'console-log-level' package we keep
// min and max log levels numeric interface used there
const [MIN_LEVEL, MAX_LEVEL] = [0, 4];

logging.setProjectId().catch(err => {
console.error(`failed to set logging project id ${err}`);
});
logging.setDetectedResource().catch(err => {
console.error(`failed to discover resource metadata ${err}`);
});

// eslint-disable-next-line @typescript-eslint/no-var-requires
const pjson = require('../../package.json');

const LEVEL_NAMES: consoleLogLevel.LogLevelNames[] = [
'fatal',
'error',
'warn',
'info',
'debug',
'trace',
];

function logLevelToName(level?: number): consoleLogLevel.LogLevelNames {
if (level === undefined) {
level = defaultConfig.logLevel;
} else if (level < 0) {
level = 0;
} else if (level > 4) {
level = 4;
export class Logger {
private log: LogSync;
private severityThreshold: number;

constructor(readonly level?: number) {
if (level === undefined) {
level = defaultConfig.logLevel;
}
if (level < MIN_LEVEL) {
level = MIN_LEVEL;
} else if (level > MAX_LEVEL) {
level = MAX_LEVEL;
}
this.severityThreshold = level;
this.log = logging.logSync(pjson.name);
}

debug(msg: string) {
if (this.severityThreshold > 3) {
this.log.debug(this.log.entry(this.toOneLine(msg)));
}
}

info(msg: string) {
if (this.severityThreshold > 2) {
this.log.info(this.log.entry(this.toOneLine(msg)));
}
}

warn(msg: string) {
if (this.severityThreshold > 1) {
this.log.warning(this.log.entry(this.toOneLine(msg)));
}
}

error(msg: string) {
if (this.severityThreshold > 0) {
this.log.error(this.log.entry(this.toOneLine(msg)));
}
}

private toOneLine(msg: string): string {
const temp = msg.replace('\r\n', '\\r\\n');
return temp.replace('\n', '\\n');
}
return LEVEL_NAMES[level];
}

export function createLogger(level?: number) {
return consoleLogLevel({
stderr: true,
prefix: pjson.name,
level: logLevelToName(level),
});
export function createLogger(level?: number): Logger {
return new Logger(level);
}

0 comments on commit 6b96e00

Please sign in to comment.