9

I generated fastify project from fastify cli then I really want to use the logger system and write it into the file

The code below is the way I try but when I send the request it does not write any log file yet and the system does not create any file also.

import { join } from 'path';
import AutoLoad, {AutoloadPluginOptions} from 'fastify-autoload';
import { FastifyLoggerOptions, FastifyPluginAsync } from 'fastify';

export type AppOptions = {
  // Place your custom options for app below here.
} & Partial<AutoloadPluginOptions> & Partial<FastifyLoggerOptions>;

const app: FastifyPluginAsync<AppOptions> = async (
    fastify,
    opts
): Promise<void> => {
  // Place here your custom code!
  opts.level = 'info'
  opts.file = 'logger'
  fastify.log.info('Test log')
  // Do not touch the following lines

  // This loads all plugins defined in plugins
  // those should be support plugins that are reused
  // through your application
  void fastify.register(AutoLoad, {
    dir: join(__dirname, 'plugins'),
    options: opts
  })

  // This loads all plugins defined in routes
  // define your routes in one of these
  void fastify.register(AutoLoad, {
    dir: join(__dirname, 'routes'),
    options: opts
  })

};

export default app;
export { app }

the opts.file is the place I put the file path to write all the log of the request.

EgoistDeveloper
  • 775
  • 2
  • 13
  • 37
MaiChinu
  • 103
  • 4

1 Answers1

1

When you deploy the app on production you need a server.js file that you invoke with node. Below is the file that you can place next to app.ts which instantiates a Fastify app instance and configure logging for you.

 'use strict'
    
    // Read the .env file.
    require('dotenv').config()
    
    // Require the framework
    const Fastify = require('fastify')
    
    // Require library to exit fastify process, gracefully (if possible)
    const closeWithGrace = require('close-with-grace')
    
    // Instantiate Fastify with some config
    const app = Fastify({
      logger: { 
        level: 'info', 
        file: process.env.LOG_FILE  || './app.log'
      }
    })
    
    // Register your application as a normal plugin.
    const appService = require('../dist/app.js')
    app.register(appService)
    
    
    // delay is the number of milliseconds for the graceful close to finish
    const closeListeners = closeWithGrace({ delay: 500 }, async function ({ signal, err, manual }) {
        if (err) {
          app.log.error(err)
        }
        await app.close()
      })
      
      app.addHook('onClose', (instance, done) => {
        closeListeners.uninstall()
        done()
      })
      
      // Start listening.
      app.listen({ port: process.env.PORT || 3000, host: '0.0.0.0' }, (err) => {
        if (err) {
          app.log.error(err)
          process.exit(1)
        }
      })
    
      
Alexander Suraphel
  • 10,103
  • 10
  • 55
  • 90