@baronote/logger

1.2.22 • Public • Published

@baronote/logger

logger

Description

winston, morgan를 이용한 logger 별도의 설정없이 사용을 위해 구성

Logger 사용 방식 변경
Trace,Pid 기본 표시 -> 설정 방식으로 변경

Installation

$ npm i @baronote/logger 
// express 에서 사용할 경우 다음과 같이 사용하면 log는 별도 import 불필요
import {morganMiddleware} from "@baronote/logger";

// middleware 사용 미사용 시
import "@baronote/logger"

Configure

로그 출력 구성
default >>[YYYYMMDD HH:mm:ss.SSS] [LogType] ▷ Message
pidOn >> [YYYYMMDD HH:mm:ss.SSS] [LogType] [PID] ▷ Message
TraceOn >> [YYYYMMDD HH:mm:ss.SSS] [traceFile:line] [LogType] ▷ Message

process.env.NODE_ENV 구성에 따른 level

production : 'info' debug, http를 제외한 로그가 콘솔에 표시 됩니다.

그외(dev,test ...) : debug, http를 포함한 로그가 콘솔에 표시 됩니다.
  • maxSize : 2mb
  • maxFiles : 30 day
  • location : ${ROOT_DIR}\logs
  • files
    • ${NODE_ENV}-${DATETIME}.log : info 레벨의 로그가 적재
    • ${NODE_ENV}-${DATETIME}-error.log : error 레벨의 로그가 적재
    • ${NODE_ENV}-${DATETIME}-http.log : http 레벨의 로그가 적재
      단, http 로그의 경우 morganMiddleware를 적용한 경우에만 적재 됩니다.
    • 그 외 (.${HASH}-audit.json) : maxFiles 옵션으로 인해 로그에 대한 관리를 위해 생성되는 파일로 존재하지 않을 경우 로그파일 삭제,압축 등 작업이 이루어지지 않습니다.

Example

Trace or Pid 출력 설정 (global)

import "@baronote/logger";
isTrace = true;
isPid = true;

log.i('normal "info" Log example');
log.w('normal "warn" Log example');
log.e('normal "error" Log example');
log.d('normal "debug" Log example');

Trace or Pid 출력 설정 (function)

import {pidOn, traceOn} from "@baronote/logger";
traceOn();
pidOn();

log.i('normal "info" Log example');
log.w('normal "warn" Log example');
log.e('normal "error" Log example');
log.d('normal "debug" Log example');

일반 사용 예시 입니다.

import "@baronote/logger";

log.i('normal "info" Log example');
log.w('normal "warn" Log example');
log.e('normal "error" Log example');
log.d('normal "debug" Log example');
result :
    [20220830 11:01:48.632] [sqlExample.js:3] [info] [12108] ▷ normal "info" Log example
    [20220830 11:01:48.634] [sqlExample.js:4] [warn] [12108] ▷ normal "warn" Log example
    [20220830 11:01:48.635] [sqlExample.js:5] [error] [12108] ▷ normal "error" Log example
    [20220830 11:01:48.636] [sqlExample.js:6] [debug] [12108] ▷ normal "debug" Log example

인자값 예시 입니다.

import "@baronote/logger";

log.i('argument Number print example', 1234);
log.i('argument String print example', 'example');
log.i('argument Short Object print example', {example: 'test'});
log.i('argument Array print example', [1, 2, 3, 4]);
log.i('argument Long Object print example', {example: 'test', example2: {object: 'long', object2: 'long2'}});
log.i('Mult argument print example', 1234, 'example', {example: 'test'}, [1, 2, 3, 4]);

// 그외 출력은 ``를 이용한 방식 사용
log.i(`${'example'} ==> ${{example: 'test'}} || ${JSON.stringify({example: 'test'})}`);
result :
    [20220830 11:15:12.156] [sqlExample.js:4] [info] [14080] ▷ argument Number print example 1234 
    [20220830 11:15:12.157] [sqlExample.js:5] [info] [14080] ▷ argument String print example example 
    [20220830 11:15:12.159] [sqlExample.js:6] [info] [14080] ▷ argument Short Object print example {"example":"test"}
    [20220830 11:15:12.160] [sqlExample.js:7] [info] [14080] ▷ argument Array print example  [1,2,3,4] 
    [20220830 11:16:39.240] [sqlExample.js:9] [info] [14080] ▷ argument Long Object print example 
    {
    "example": "test",
        "example2": {
            "object": "long",
            "object2": "long2"
        }
    }

    [20220830 11:15:12.162] [sqlExample.js:10] [info] [14080] ▷ Mult argument print example 1234 example {"example":"test"} [1,2,3,4] 
    [20220830 11:15:12.162] [sqlExample.js:11] [info] [14080] ▷ example ==> [object Object] || {"example":"test"}

변수 사용 예시 입니다.

import "@baronote/logger";

log.i(1234);
log.i({example: 'test'});
log.i([1, 2, 3, 4]);
log.i({example: 'test', example2: {object: 'long', object2: 'long2'}});
log.i(1234, 'example', {example: 'test'}, [1, 2, 3, 4]);
result :
    [20220830 11:47:32.176] [sqlExample.js:3] [info] [12976] ▷  1234 
    [20220830 11:47:32.178] [sqlExample.js:4] [info] [12976] ▷  {"example":"test"}
    [20220830 11:47:32.179] [sqlExample.js:5] [info] [12976] ▷   [1,2,3,4] 
    [20220830 11:47:32.180] [sqlExample.js:6] [info] [12976] ▷  
    {
        "example": "test",
        "example2": {
            "object": "long",
            "object2": "long2"
        }
    }
    
    [20220830 11:47:32.182] [sqlExample.js:7] [info] [12976] ▷  1234 example {"example":"test"} [1,2,3,4]

에러 예시 입니다.

import "@baronote/logger";

let err = new Error('error Example..');
log.e(err);
throw err;
result :
    [20220830 11:42:27.229] [sqlExample.js:5] [error] [11272] ▷ Error: error Example..
        at file:///C:\\sqlExample.js:4:11
        at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
        at async Promise.all (index 0)
        at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
        at async loadESM (node:internal/process/esm_loader:88:5)
        at async handleMainPromise (node:internal/modules/run_main:61:12) 
    [20220830 11:42:27.254] [SYSTEM] [error] [11272] ▷ uncaughtException: error Example..
    Error: error Example..
        at file:///C:\\sqlExample.js:4:11
        at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
        at async Promise.all (index 0)
        at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
        at async loadESM (node:internal/process/esm_loader:88:5)
        at async handleMainPromise (node:internal/modules/run_main:61:12) {}Error: error Example..
        at file:///C:\\sqlExample.js:4:11
        at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
        at async Promise.all (index 0)
        at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
        at async loadESM (node:internal/process/esm_loader:88:5)
        at async handleMainPromise (node:internal/modules/run_main:61:12) Tue Aug 30 2022 11:42:27 GMT+0900 (대한민국 표준시)
    {
        "pid": 11272,
        "uid": null,
        "gid": null,
        "cwd": "C:\\",
        "execPath": "C:\\Program Files\\nodejs\\node.exe",
        "version": "v16.16.0",
        "argv": [
            "C:\\Program Files\\nodejs\\node.exe",
            "C:\\sqlExample.js"
        ],
        "memoryUsage": {
            "rss": 36016128,
            "heapTotal": 11935744,
            "heapUsed": 8501576,
            "external": 1397463,
            "arrayBuffers": 216490
        }
    }
    {"loadavg":[0,0,0],"uptime":7651} [[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]]



Express Logger 사용

morgan 로그는 combined 을 기본으로 사용합니다.

:remote-addr - :remote-user ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"

import express from 'express';
import {morganMiddleware} from "@baronote/logger";

const app = express();
const port = process.env.PORT || 5000;

app.use(morganMiddleware());

app.all('/info', (req, res, next) => {
    log.i('info test');
    res.status(200).send({
        message: "info test!"
    })
});

app.listen(port, () => log.i(`Server Start Listening on port ${port}`));
result :
    [20220830 11:23:59.351] [expressExample.js:16] [info] [13444] ▷ Server Start Listening on port 5000 
    [20220830 11:24:17.066] [expressExample.js:10] [info] [13444] ▷ info test 
    [20220830 11:24:17.075] [Express] [http] [13444] ▷ ::1 - - "GET /test/info HTTP/1.1" 200 24 "-" "PostmanRuntime/7.29.2"

History

1.1.x
### 1.1.0 - 수정 : README 글로벌 안내, configure 내용 추가 - 수정 : `express Middleware` 미 사용시 http 로그 파일 생성 제어 - 수정 : `morganMiddleware` 사용 방식 변수형 -> 함수형으로 변경

1.1.2

  • 추가 : 모듈 난독화

1.1.3

  • 수정 : 기본 *.log 파일의 적재 레벨 관련 수정

1.1.4

  • 수정 : import 방식 변경

1.1.5

  • 수정 : node:process 관련 수정

1.1.6

  • 수정 : 기본 로그 출력 포멧 변경
  • 추가 : traceOn, pidOn function
  • 수정 : process 패키지 미사용 방식으로 변경

1.1.7

  • 수정 : 오탈자 수정

1.1.8

  • 수정 : 라이센스 주소
  • 수정 : install 수정
  • 추가 : 히스토리 접기 추가

1.1.9

  • 수정 : boolean 형 출력 안되는 문제 수정

1.1.22

  • 추가 : 로그 kafka 전송 옵션
  • 추가 : TraceID 설정 추가 ( Rest, gRPC )

LICENSE

MIT

(The MIT License)

Copyright (c) 2022 baronote <jwpark@sorizava.com>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Package Sidebar

Install

npm i @baronote/logger

Weekly Downloads

11

Version

1.2.22

License

MIT

Unpacked Size

61.8 kB

Total Files

12

Last publish

Collaborators

  • belucent0
  • dcr21
  • june1985
  • bis0212
  • _baronote