loopbackio / loopback-next

LoopBack makes it easy to build modern API applications that require complex integrations.
https://loopback.io
Other
4.96k stars 1.07k forks source link

How to generate error logs with loopback 4? #3975

Closed prth-123 closed 4 years ago

prth-123 commented 5 years ago

Hello Team, I want to auto generate error logs if any error comes from my API and store them in any file or in database. I have already looked in log-extensions but was not that much helpful.

dhmlau commented 5 years ago

@prth-123, I assume you're referring to this log-extension. Could you please elaborate more about why the log-extension is not helpful? Thanks.

dhmlau commented 5 years ago

Transferring to loopback-next repo.

prth-123 commented 5 years ago

@dhmlau , Yes i was refering to log-extension but i don't think i need to achieve this. I just want to create a log file in which i want to enter error logs whenever generated from any REST API.

sureshkodur commented 5 years ago

Hi, @dhmlau , I want to create a log file in loopback4 . Can anyone help me. Thanks in advance

marioestradarosa commented 5 years ago

@prth-123 , @sureshkodur I don't understand why the log-extension is not helpful to you either, but you can use an external package if you want, such as winston. Here are the details:

Step 1 npm install winston --save and npm install winston-daily-rotate-file

Optional you can use moment for timeStamps, but also new Date() can work npm install moment --save

Step 2 I personally create an environment directory and inside an environment.ts file with the following configuration , i usually replace mylogs directory with the application name or micro service name to keep track of it later on on the master logs directory.

Note: replace ../logs with ./logs if you want the log directory not in the parent directory, I use this one because I have multiple micro services that shares the same logs directory.

export const LogConfig = {
  logName: 'transfers',
  logDirectory: '../logs/mylogs/',
  logFileWarning: 'mylogs-%DATE%.log',
  logFileIssue: 'mylog-issues-%DATE%.log',
  logDatePattern: 'YYYY-MM-DD',
};

Step 3 Add the following code in the application.ts file after the imports and before the application class definition:


import {LogConfig} from './environment';

import * as moment from 'moment';
//Winston Import
import * as winston from 'winston';
import * as DailyRotateFile from 'winston-daily-rotate-file';

//define custom format for logs
const customFormat = winston.format.combine(
  winston.format.splat(),
  winston.format.simple(),
  winston.format.align(),
  winston.format.printf(
    info =>
      `${moment().format('YYYY-MM-DD HH:mm:ss:SS')} - ${info.level}: ${
        info.message
      }`,
  ),
);

//logger for the acct-statdates
winston.loggers.add(LogConfig.logName, {
  exitOnError: false,
  format: winston.format.combine(customFormat),
  transports: [
    new DailyRotateFile({
      filename: LogConfig.logDirectory + LogConfig.logFileWarning,
      datePattern: LogConfig.logDatePattern,
      zippedArchive: true,
      level: 'info',
    }),
    new DailyRotateFile({
      filename: LogConfig.logDirectory + LogConfig.logFileIssue,
      datePattern: LogConfig.logDatePattern,
      zippedArchive: true,
      level: 'warn',
    }),
    new winston.transports.Console({
      level: 'info',
    }),
  ],
});

Step 4 In any of your controllers or repositories etc., you first import the log configuration file and the winston package:

import {
  LogConfig,
} from '../environment/environment';
import * as winston from 'winston';

Then in the same controller or repository file, declare the following variable in the class, before the constructor method:

  public logger = winston.loggers.get(LogConfig.logName);

Step 5

Finally, you can call logger to log in the file with automatic rotation info, warning or any error like so:

   / / INFO LEVEL OUTPUT
    this.logger.info('INIT: Request to make a transfer');

    // ERROR LEVEL OUTPUT
    // errorMessage probably is something that was catched 
     this.logger.error(`Error: ${errorMessage}`);

    // WARNING LEVEL OUTPUT
     this.logger.warn(`That did not work !!`);
prth-123 commented 5 years ago

@marioestradarosa Thanks for your assistance

prth-123 commented 5 years ago

@marioestradarosa i have tried to understand and implement log extension code, but i was not successful in this. So if you can explain me further then it will helpful for me. Thanks And I will try to use winston module for this, hope i will work as per my expectations.

achrinza commented 4 years ago

Closing due to inactivity. Please open a new issue if the problem persists.