[Rust] log4rs: 로깅 라이브러리

log4rs는 편리한 로깅 처리 기능을 제공해주는 라이브러리다.
자바의 log4j를 따라한 것 같다.

종속성은 log, log4rs가 필요하다.

그리고 로깅 환경 설정을 해야하는데, 2가지 방식이 있다. 하나는 코드상에서 다 처리하는 것이고, 하나는 yaml로 구성하는 것이다.
yaml이 더 깔끔한게 보기 좋아서 난 yaml을 쓴다.
내 설정은 이렇다.

# Scan this file for changes every 30 seconds
refresh_rate: 30 seconds

appenders:
  # An appender named "stdout" that writes to stdout
  stdout:
    kind: console
    filters:
      - kind: threshold
        level: debug

  trace:
    kind: file
    filters:
      - kind: threshold
        level: trace
    path: "logs/trace.log"
    encoder:
      pattern: "{d(%Y-%m-%d %H:%M:%S %Z)(utc)} - {l}:{m}{n}"

  debug:
    kind: file
    filters:
      - kind: threshold
        level: debug
    path: "logs/debug.log"
    encoder:
      pattern: "{d(%Y-%m-%d %H:%M:%S %Z)(utc)} - {l}:{m}{n}"

  info:
    kind: file
    filters:
      - kind: threshold
        level: info
    path: "logs/info.log"
    encoder:
      pattern: "{d(%Y-%m-%d %H:%M:%S %Z)(utc)} - {l}:{m}{n}"

  warn:
    kind: file
    filters:
      - kind: threshold
        level: warn
    path: "logs/warn.log"
    encoder:
      pattern: "{d(%Y-%m-%d %H:%M:%S %Z)(utc)} - {l}:{m}{n}"

  error:
    kind: file
    filters:
      - kind: threshold
        level: error
    path: "logs/error.log"
    encoder:
      pattern: "{d(%Y-%m-%d %H:%M:%S %Z)(utc)} - {l}:{m}{n}"

# Set the default logging level to "warn" and attach the "stdout" appender to the root
root:
  appenders:
    - stdout
    - trace
    - debug
    - info
    - warn
    - error

appenders 목록으로 출력 수준들을 지정해놓고 root에 한번에 등록했다.
그리고 로그 레벨은 trace>debug>info>warn>error의 순서를 따른다.
저기서 오른쪽에 해당하는 로그는 전부 왼쪽 레벨에서도 뜬다. 그 반대는 성립하지 않는다.

난 debug까지의 로그들은 전부 표준 입력에 나오도록 stdout appender를 정의했고,
모든 레벨들은 전부 각각의 파일에 출력하도록 했다.

그리고 사용할 때는 이렇게 하면 된다.
설정파일을 init_file로 로드하면 log4rs의 작업은 완전 끝이다.

그럼 log의 로깅 함수들, debug, error, info, ..등을 사용할때마다 log4rs로 설정된 목적지에 따라 다 출력, 기록이 된다.

그래서 저대로 실행을 시키면

표준 출력에도 그대로 잘 뜰 것이고

로그 파일들에도

잘 기록될 것이다.

그럼 이제 저것들을 잘 보기만 하면 되는 것이다.


참조
https://github.com/estk/log4rs
https://docs.rs/log/0.4.8/log/