Logging | Fastify (2024)

Logging

Enable logging

Logging is disabled by default, and you can enable it by passing { logger: true} or { logger: { level: 'info' } } when you create a Fastify instance. Notethat if the logger is disabled, it is impossible to enable it at runtime. We useabstract-logging for thispurpose.

As Fastify is focused on performance, it usespino as its logger, with the default loglevel, when enabled, set to 'info'.

Enabling the production JSON logger:

const fastify = require('fastify')({
logger: true
})

Enabling the logger with appropriate configuration for both local developmentand production and test environment requires a bit more configuration:

const envToLogger = {
development: {
transport: {
target: 'pino-pretty',
options: {
translateTime: 'HH:MM:ss Z',
ignore: 'pid,hostname',
},
},
},
production: true,
test: false,
}
const fastify = require('fastify')({
logger: envToLogger[environment] ?? true // defaults to true if no entry matches in the map
})

⚠️ pino-pretty needs to be installed as a dev dependency, it is not includedby default for performance reasons.

Usage

You can use the logger like this in your route handlers:

fastify.get('/', options, function (request, reply) {
request.log.info('Some info about the current request')
reply.send({ hello: 'world' })
})

You can trigger new logs outside route handlers by using the Pino instance fromthe Fastify instance:

fastify.log.info('Something important happened!');

If you want to pass some options to the logger, just pass them to Fastify.You can find all available options in thePino documentation.If you want to specify a file destination, use:

const fastify = require('fastify')({
logger: {
level: 'info',
file: '/path/to/file' // Will use pino.destination()
}
})

fastify.get('/', options, function (request, reply) {
request.log.info('Some info about the current request')
reply.send({ hello: 'world' })
})

If you want to pass a custom stream to the Pino instance, just add a streamfield to the logger object.

const split = require('split2')
const stream = split(JSON.parse)

const fastify = require('fastify')({
logger: {
level: 'info',
stream: stream
}
})

By default, Fastify adds an ID to every request for easier tracking. If the"request-id" header is present its value is used, otherwise a new incremental IDis generated. See Fastify FactoryrequestIdHeader and Fastify FactorygenReqId for customization options.

The default logger is configured with a set of standard serializers thatserialize objects with req, res, and err properties. The object receivedby req is the Fastify Request object, while the objectreceived by res is the Fastify Reply object. This behaviorcan be customized by specifying custom serializers.

const fastify = require('fastify')({
logger: {
serializers: {
req (request) {
return { url: request.url }
}
}
}
})

For example, the response payload and headers could be logged using the approachbelow (even if it is not recommended):

const fastify = require('fastify')({
logger: {
transport: {
target: 'pino-pretty'
},
serializers: {
res (reply) {
// The default
return {
statusCode: reply.statusCode
}
},
req (request) {
return {
method: request.method,
url: request.url,
path: request.routerPath,
parameters: request.params,
// Including the headers in the log could be in violation
// of privacy laws, e.g. GDPR. You should use the "redact" option to
// remove sensitive fields. It could also leak authentication data in
// the logs.
headers: request.headers
};
}
}
}
});

Note: In certain cases, the Reply object passed to the resserializer cannot be fully constructed. When writing a custom res serializer,it is necessary to check for the existence of any properties on reply asidefrom statusCode, which is always present. For example, the existence ofgetHeaders must be verified before it can be called:

const fastify = require('fastify')({
logger: {
transport: {
target: 'pino-pretty'
},
serializers: {
res (reply) {
// The default
return {
statusCode: reply.statusCode
headers: typeof reply.getHeaders === 'function'
? reply.getHeaders()
: {}
}
},
}
}
});

Note: The body cannot be serialized inside a req method because therequest is serialized when we create the child logger. At that time, the body isnot yet parsed.

See an approach to log req.body

app.addHook('preHandler', function (req, reply, done) {
if (req.body) {
req.log.info({ body: req.body }, 'parsed body')
}
done()
})

Note: Care should be taken to ensure serializers never throw, as an errorthrown from a serializer has the potential to cause the Node process to exit.See the Pino documentationon serializers for more information.

Any logger other than Pino will ignore this option.

You can also supply your own logger instance. Instead of passing configurationoptions, pass the instance. The logger you supply must conform to the Pinointerface; that is, it must have the following methods: info, error,debug, fatal, warn, trace, silent, child and a string property level.

Example:

const log = require('pino')({ level: 'info' })
const fastify = require('fastify')({ logger: log })

log.info('does not have request information')

fastify.get('/', function (request, reply) {
request.log.info('includes request information, but is the same logger instance as `log`')
reply.send({ hello: 'world' })
})

The logger instance for the current request is available in every part of thelifecycle.

Log Redaction

Pino supports low-overhead log redaction for obscuringvalues of specific properties in recorded logs. As an example, we might want tolog all the HTTP headers minus the Authorization header for security concerns:

const fastify = Fastify({
logger: {
stream: stream,
redact: ['req.headers.authorization'],
level: 'info',
serializers: {
req (request) {
return {
method: request.method,
url: request.url,
headers: request.headers,
hostname: request.hostname,
remoteAddress: request.ip,
remotePort: request.socket.remotePort
}
}
}
}
})

See https://getpino.io/#/docs/redaction for more details.

Logging | Fastify (2024)
Top Articles
FTC Says TruthFinder, Instant Checkmate Deceived Users About Background Report Accuracy, Violated FCRA While Marketing Reports for Employee and Tenant Screening
Grants Administration
Housing near Juneau, WI - craigslist
Wordscapes Level 5130 Answers
Www Craigslist Louisville
2022 Apple Trade P36
Paula Deen Italian Cream Cake
Tribune Seymour
Phillies Espn Schedule
Oxford House Peoria Il
Evangeline Downs Racetrack Entries
Jack Daniels Pop Tarts
Binghamton Ny Cars Craigslist
Suffix With Pent Crossword Clue
Craigslist Panama City Fl
Elemental Showtimes Near Cinemark Flint West 14
SF bay area cars & trucks "chevrolet 50" - craigslist
Nearest Walgreens Or Cvs Near Me
*Price Lowered! This weekend ONLY* 2006 VTX1300R, windshield & hard bags, low mi - motorcycles/scooters - by owner -...
Qual o significado log out?
Talkstreamlive
Atlases, Cartography, Asia (Collection Dr. Dupuis), Arch…
Bn9 Weather Radar
Piri Leaked
Www Pointclickcare Cna Login
Page 2383 – Christianity Today
13301 South Orange Blossom Trail
Carroway Funeral Home Obituaries Lufkin
Cona Physical Therapy
Craftybase Coupon
30+ useful Dutch apps for new expats in the Netherlands
Craftsman Yt3000 Oil Capacity
Craigslist/Phx
2487872771
Laveen Modern Dentistry And Orthodontics Laveen Village Az
James Ingram | Biography, Songs, Hits, & Cause of Death
Mkvcinemas Movies Free Download
Average weekly earnings in Great Britain
Wcostream Attack On Titan
Nextdoor Myvidster
Quality Tire Denver City Texas
Goodwill Houston Select Stores Photos
Pitco Foods San Leandro
School Tool / School Tool Parent Portal
Case Funeral Home Obituaries
The Minneapolis Journal from Minneapolis, Minnesota
Lacy Soto Mechanic
Trivago Anaheim California
Martha's Vineyard – Travel guide at Wikivoyage
How to Install JDownloader 2 on Your Synology NAS
Latest Posts
Article information

Author: Manual Maggio

Last Updated:

Views: 5357

Rating: 4.9 / 5 (69 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Manual Maggio

Birthday: 1998-01-20

Address: 359 Kelvin Stream, Lake Eldonview, MT 33517-1242

Phone: +577037762465

Job: Product Hospitality Supervisor

Hobby: Gardening, Web surfing, Video gaming, Amateur radio, Flag Football, Reading, Table tennis

Introduction: My name is Manual Maggio, I am a thankful, tender, adventurous, delightful, fantastic, proud, graceful person who loves writing and wants to share my knowledge and understanding with you.