nginx의 로그 포맷 수정하기

janghoosa·2022년 8월 8일
0

Infra

목록 보기
3/4
post-thumbnail

nginx의 로그

nginx를 다운받고서 기본 설정으로 실행을 하게 되면 /etc/nginx/nginx.conf의 설정파일을 읽고 그 안에 있는 Virtual Host Configs에서 sites-enabled에 있는 default 파일을 읽어 80포트의 서버를 열게 된다.

sites-enabled에 있는 설정 파일은 사용중인 설정 파일이면서 sites-available에 있는 설정 파일을 심볼릭 링크로 연결시켜놓은 파일이다.

★따라서 우리가 설정을 바꾸려면 sites-available에 있는 설정을 바꾸어야 한다.

로깅 설정을 바꾸는 방법은?

아래 링크는 nginx docs에 있는 로깅 가이드니 보고 싶으신 분은 보세요!
https://docs.nginx.com/nginx/admin-guide/monitoring/logging/

하지만 로깅에 대한 설정은 nginx.conf에 Logging Settings라는 항목에 있으니 이 부분을 설정해주면 된다.

기본적인 로깅 세팅은 다음과 같이 접속 로그와 에러 로그를 남기게 되어있다.

/etc/nginx/nginx.conf
		# ~~~
        
 		##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;
        
        # ~~~

우선 access_log를 보자.
로그 포맷은 명시하지 않았을 경우에는 combined format 이라는 형태로 되어있고 모양은 다음과 같다.

 log_format combined '$remote_addr - $remote_user [$time_local] '
           '"$request" $status $body_bytes_sent '
           '"$http_referer" "$http_user_agent" "$gzip_ratio"';
  • remote_addr: 접속한 주소
  • remote_user: 접속한 유저 정보 (http 헤더 정보)
  • time_local: 서버 컴퓨터 로컬 시간
  • request: HTTP Method 및 url, HTTP 버전 정보
  • status: 응답 코드
  • body_bytes_sent: 전송한 body의 바이트 크기
  • http_referer: referer 정보, 보통 요청 이전의 페이지의 url를 가지고 있다.
  • http_user_agent: 사용자의 소프트웨어 식별 정보
  • gzip_ratio: 콘텐츠를 전송할 때 압축하는 기능인 contents compression에서 gzip의 비율이 얼마나 되는지를 나타낸다.

이런 정보들이 기본적으로 사용되고 있다. 이 부분에서 우리가 추가 할 수 있는 변수들은 다음과 같다.

  • $bytes_sent
    the number of bytes sent to a client
  • $connection
    connection serial number
  • $connection_requests
    the current number of requests made through a connection (1.1.18)
  • $msec
    time in seconds with a milliseconds resolution at the time of the log write
  • $pipe
    “p” if request was pipelined, “.” otherwise
  • $request_length
    request length (including request line, header, and request body)
  • $request_time
    request processing time in seconds with a milliseconds resolution; time elapsed between the first bytes were read from the client and the log write after the last bytes were sent to the client
  • $status
    response status
  • $time_iso8601
    local time in the ISO 8601 standard format
  • $time_local
    local time in the Common Log Format

로깅을 바꿔보자

log_format timed_combined '$remote_addr - $remote_user [$time_local] '
        '"$request" $status $body_bytes_sent '
        '"$http_referer" "$http_user_agent" '
        'rt $request_time urt $upstream_response_time';
        access_log /var/log/nginx/access.log timed_combined;

내가 nginx 로깅에서 필요했던 부분은 request_time이다. 이부분을 추가해서 다음과 같은 log_format을 만들고 적용시켰다.

그리고 /var/log/access.log 를 확인하면 원하는 것처럼 잘 나오는 것을 볼 수 있다.

profile
백엔드 개발자 지망생입니다 :)

0개의 댓글