Allows printing logs to stdout
, stderr
for further action in Google Cloud platform. Given that log agent ingests logs from stdout
streams when running in GKE.
![Runkit](https://badgen.net/badge/runkit/playground/cyan)
Precaution
A logger makes use of async_hooks
module which is currently experimental. However, the use of async_hooks
mechanism was at basic.
Installation
npm install --save gc-json-logger
yarn add gc-json-logger
View in Google Cloud Logging
![Google Cloud Logging](https://github.com/igrek8/gc-json-logger/raw/HEAD/./media/google-cloud-logging.png)
Integration
const { Logger } = require('gc-json-logger');
const { createServer } = require('http');
let job = 0;
function scheduleJob() {
const logger = Logger.getLogger();
logger.info('scheduling job');
setTimeout(() => {
logger.info('job done');
}, 3000);
}
const server = createServer((_, res) => {
job++;
const logger = new Logger(job);
Logger.setLogger(logger);
logger.info('creating a new job');
scheduleJob();
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ id: job, status: 'scheduled' }));
});
server.listen(8080);
{
"severity": "INFO",
"time": "2022-12-03T10:00:00.000Z",
"message": "creating a new job",
"logging.googleapis.com/operation": { "id": 1 } // <- always includes context id
}
{
"severity": "INFO",
"time": "2022-12-03T10:00:00.398Z",
"message": "scheduling job",
"logging.googleapis.com/operation": { "id": 1 } // <- always includes context id
}
{
"severity": "INFO",
"time": "2022-12-03T10:00:01.000Z",
"message": "job done",
"logging.googleapis.com/operation": { "id": 1 } // <- always includes context id
}