Python/2.7 information

로그 찍기.

qkqhxla1 2017. 3. 30. 20:25

파이썬에는 logging이라는 로그를 위한 모듈이 있다. 

몇가지 자주 쓰이는 것(자주 쓰이는것처럼 보이는 것)만 적어보려고 함..


1. logging.getLogger('이름') 으로 로그파일을 만들 수 있다. 로그라는걸 알려주기위해 .log를 확장자로 하자.


2. logging.Formatter('') 으로 로그의 형식을 지정할 수 있다. 아래 참고에 적어놓은 공식홈페이지에서 가져온 예제이다.

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

포맷이 특이하다. %(name)같은건 예약어인지 선언안하고 쓸수 있다. 저런식으로 포맷을 설정하고

logger.debug('debug message')

처럼 실행하면 

2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message

이렇게 나온다. 시간,이름, debug, message가 차례로 출력되는걸 확인할수 있다. 이걸로 포맷을 설정하자.


3. 로그파일 하나에 계속 출력을 하다 보면 파일이 너무 커지거나 해서 죽을 수가 있다. 열려고 해도 안열릴때도 있고.. 이럴 때를 대비해서 파일과 관련된 설정을 할 수 있다.

logging.handlers.RotatingFileHandler라는걸로 설정할 수 있다. 공식문서

logging.handlers.RotatingFileHandler('파일이름', maxBytes='파일의 최대 바이트 크기', backupCount='백업할 개수')


처럼 쓸수 있고, backupCount같은경우 5로 설정하면 파일의 최대 크기가 넘어갈 경우 로그 파일 이름이 mylog.log라고 가정하면 mylog.log, mylog.log.1, mylog.log.2 ~~~mylog.log.5까지 생성이 된다. 


Rotating이라는 이름에서도 알수 있듯이 1,2,3,4,5가 돌아가면서 덮어씌워진다.


이것들 말고는 https://aykutakin.wordpress.com/2013/08/06/logging-to-console-and-file-in-python/에 사용예시가 잘 설명되어있는데 StreamHandler()라는 핸들러도 있다.


이걸로 핸들러를 만들면 콘솔에 로그가 출력된다.(print한것처럼.) 글쓰면서 생각한건데 바로 이전 글인 유닛테스트를 할때도 활용할수 있을것 같다. 


4. 에러 출력하기.

일반적으로 에러가 발생하면 에러메시지를 내뱉고 프로그램이 죽는데, 이 에러메시지를 프로그램을 죽이지 않고도 출력이 가능하다. try except를 이용해서 출력하면 된다. 

http://stackoverflow.com/questions/3702675/how-to-print-the-full-traceback-without-halting-the-program

에 예시가 잘 나와있다. traceback모듈의 print_exception을 이용하면된다.

import traceback
import sys

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        exc_info = sys.exc_info()

        try:
            raise TypeError("Again !?!")
        except:
            pass

    finally:
        traceback.print_exception(*exc_info)
        del exc_info

print 'program still alive'

위의 것들을 이용해 나만의 로그를 기초적인틀만 만들어보면..

# -*- coding: utf-8 -*-
import logging
import logging.handlers

class myLog:
    def __init__(self, filename):
        self.logger = logging.getLogger(filename)
        fomatter = logging.Formatter('[%(asctime)s : %(levelname)s] %(message)s')
        fileMaxByte = 1024 * 1024 * 5 #5mb
        fileHandler = logging.handlers.RotatingFileHandler(filename, maxBytes=fileMaxByte, backupCount=5)
        fileHandler.setFormatter(fomatter)
        self.logger.addHandler(fileHandler)
        self.logger.setLevel(logging.DEBUG)

    def write(self, msg):
        self.logger.error(msg)

log = myLog('mylog.log')
log.write('something error!')

처럼 만들수 있다.(확장할것들이 많다.)


참고.

logging module : https://docs.python.org/2/howto/logging.html


traceback : https://docs.python.org/2/library/traceback.html

'Python > 2.7 information' 카테고리의 다른 글

yield from, generator(yield) vs coroutine (python 3)  (0) 2017.04.26
mongo db  (0) 2017.04.19
유닛테스트.  (0) 2017.03.26
unittest. 테스트  (0) 2017.02.25
python smtp(메일보내기)  (0) 2016.12.14