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

fix: log to console using structured logging #780

Merged
merged 10 commits into from
Dec 20, 2021
5 changes: 3 additions & 2 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 Expand Up @@ -80,6 +81,6 @@
]
},
"engines": {
"node": ">=10.4.1"
"node": ">=10"
}
}
}
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
81 changes: 57 additions & 24 deletions src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,36 +12,69 @@
// 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();

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 < 0) {
minherz marked this conversation as resolved.
Show resolved Hide resolved
losalex marked this conversation as resolved.
Show resolved Hide resolved
level = 0;
} else if (level > 4) {
level = 4;
}
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 {
minherz marked this conversation as resolved.
Show resolved Hide resolved
return msg.replace('\n', '\\n');
minherz marked this conversation as resolved.
Show resolved Hide resolved
}
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);
}