gcp-structured-logger
v5.0.0
Published
Structured logger for GCP logging
Readme
GCP Structured Logger
Outputs structured logs that are formatted in GCP logging.
Basic Usage
Most basic usage it to create a Logging object and use the logger property.
const { Logging, LogSeverity } = require('gcp-structured-logger')
const logging = new Logging({
projectId: '<project-id>',
logName: '<label for logName>', // Useful for filtering in Log viewer
serviceContext: {
service: '<service name>', // Name that appears in Error Reporter
version: '<version>', // Optional version
},
extraLabels: { // Optional extra labels useful for more filtering
},
requestUserExtractor: () => {} // See below
})
logging.logger.info('Some log message', {
extra: 'data'
}, ['Array'])Redaction
When NODE_ENV is production, log data is passed through a redactor before being written. By default, values are replaced with a <<REDACTED> ...> string if their key looks sensitive (e.g. authorization, password, cookie, api_key, access_token) or if a string value looks like a credential (e.g. Bearer ..., ?access_token=..., Google API keys, OAuth tokens, PEM private keys).
The redactor option can be:
true(default) - use the default redactor.false- disable redaction.- A function
(parentKey, value, defaultRedactor) => any- called for every value (primitives, and objects/arrays after their contents have been redacted). Return the value unchanged to keep it, or a replacement to hide it. If the function throws or returnsundefinedfor a defined value, the value is redacted and a warning is emitted.
const logging = new Logging({
// ...
redactor: (parentKey, value, defaultRedactor) => {
if (parentKey === 'email') return '<<REDACTED>>'
return defaultRedactor(parentKey, value)
},
})Error reporting
To report errors to GCP Error Reporting the reportError method on a logger can be used.
An optional severity can also be passed in, or it is picked up from the provided error. If no severity is passed in ERROR is used.
const err = new Error('An error occurred')
logging.logger.reportError(err)
// With severity
logging.logger.reportError(err, LogSeverity.ALERT)Monitoring Node Process
These get logged out to GCP Error reporting.
// Listen out for uncaughtException (uses uncaughtExceptionMonitor in v12.17+) and unhandled Promise rejections
logging.attachToProcess(logging.logger)
// To remove from the process
const detachLogger = logging.attachToProcess(logging.logger)
detachLogger()With Express
Can be use with express as a logging middleware and error handler.
If the err has a statusCode or status property that is greater or equal to 500, then the severity of the err is set to WARNING.
const express = require('express')
const app = express()
// App setup - set port, trust proxy, etc
// Add ability to use req.log in later middleware
app.use(logger.makeLoggingMiddleware())
app.use((req, res, next) => {
req.log.debug('Incoming request')
next()
})
// Add routes
// And a final error handler if needed
app.use((req, res, next) => next({ status: 404, message: 'Not found' }))
// Report next(err)
app.use(logger.makeErrorMiddleware())With Node HTTP2 server
Can be use with node:http2 server but only for attaching a log property to a Http2ServerRequest or Http2Stream.
There is no error reporting middleware for HTTP2, so you will need to call log.reportError yourself if you want to report errors.
const http2 = require('node:http2')
const server = http2.createServer()
// With a stream
server.on('stream', logger.http2StreamListener((stream, headers) => {
stream.log.info('Incoming request')
stream.respond({ ':status': 200 })
stream.end('Hello World')
}))
// Or with a request
server.on('request', logger.http2RequestListener((req, res) => {
req.log.info('Incoming request')
res.writeHead(200)
res.end('Hello World')
}))You can also pass in a requestUserExtractor function when creating a Logging instance for setting the user of the error.
This is useful if you've attached the logged in user, etc. to the request or the headers contains some user info.
If requestUserExtractor returns no value (or is not provided), no user will be set on the reported error.
const logging = new Logging({
projectId: '<project-id>',
logName: '<label for logName>',
serviceContext: {
service: '<service name>',
},
requestUserExtractor: req => {
// Parameter is the request that log.reportError was called on
return req.get('user-id')
},
})