Форум сайта python.su
С модулем logging имею дело. Хочу сделать отступы слева для аргумента %(message)s в формате строки так , чтобы в файле значение этого аргумента было всегда правее значений двух предидущих аргументов: %(levelname)-8s %(asctime)sВот код:
import logging query = 'http://{ADDR}/query/ta?begin={BEGIN}&end={END}' log_file = 'log_file.txt' logging.basicConfig(filename=log_file, level=logging.INFO, filemode='a', format='%(levelname)-8s %(asctime)s %(message) 19s', datefmt='%Y-%m-%d %H:%M:%S') init_datetime = datetime.now().strftime('%Y%m%d') current_datetime = datetime.now().strftime('%Y%m%d') query = query.format(ADDR='some.controller.ru', BEGIN=init_datetime, END=current_datetime) logging.info(query) try: resp = request.urlopen(query) body = resp.readall() logging.info(body) except Exception: logging.error(traceback.format_exc()) # вот конкретно вывод отладочной инфы во много строк смотрися некрасиво, всё съезжает налево, после отступа на новую строку в файле.
INFO 2013-08-02 10:52:03 http://some.controller.ru/query/ta?begin=20130802&end=20130802
ERROR 2013-08-02 10:52:03 Traceback (most recent call last):
File "C:\Python32\lib\urllib\request.py", line 1140, in do_open
h.request(req.get_method(), req.selector, req.data, headers)
File "C:\Python32\lib\http\client.py", line 983, in request
self._send_request(method, url, body, headers)
File "C:\Python32\lib\http\client.py", line 1021, in _send_request
self.endheaders(body)
File "C:\Python32\lib\http\client.py", line 979, in endheaders
self._send_output(message_body)
File "C:\Python32\lib\http\client.py", line 824, in _send_output
self.send(msg)
File "C:\Python32\lib\http\client.py", line 762, in send
self.connect()
File "C:\Python32\lib\http\client.py", line 740, in connect
self.timeout, self.source_address)
File "C:\Python32\lib\socket.py", line 408, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno 11004] getaddrinfo failed
INFO 2013-08-02 10:52:03 http://some.controller.ru/query/ta?begin=20130802&end=20130802
ERROR 2013-08-02 10:52:03 Traceback (most recent call last):
File "C:\Python32\lib\urllib\request.py", line 1140, in do_open
h.request(req.get_method(), req.selector, req.data, headers)
File "C:\Python32\lib\http\client.py", line 983, in request
self._send_request(method, url, body, headers)
Отредактировано buddha (Авг. 2, 2013 10:10:48)
Офлайн
как то так можно :)
import logging, traceback def a(): def b(): return " " * " " b() def g(): return a() log_file = 'log_file.txt' logging.basicConfig(filename=log_file, level=logging.INFO, filemode='a', format='%(levelname)s %(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') try: g() except Exception: tb = traceback.format_exc() tb = "\n ".join(tb.split("\n")) logging.error(tb)
ERROR 2013-08-02 13:30:15 Traceback (most recent call last): File "<pyshell#17>", line 16, in <module> g() File "<pyshell#17>", line 9, in g return a() File "<pyshell#17>", line 6, in a b() File "<pyshell#17>", line 5, in b return " " * " " TypeError: can't multiply sequence by non-int of type 'str'
Офлайн
Выход конечно=) я так мог и через print() всё в файл повыводить… Думаю решение скрывается в правильном logging.basicConfig(format=)
Отредактировано buddha (Авг. 2, 2013 10:38:09)
Офлайн
Только использовать свой `Formatter`. А в нём переопределить `formatException` или `format`. С `basicConfig` фокус не пройдёт.
..bw
Офлайн
Не стал запариваться, взял рецепт sp3.
Офлайн
Ну не комильфо же, дело же пяти минут же, и стыдно потом не будет же.
#!/usr/bin/env python import logging def foo(): 1/0 def bar(): foo() def main(): logging.info('multi-\nline\nmessage') bar() class MyFormatter(logging.Formatter): def format(self, record): message = logging.Formatter.format(self, record) if '\n' in message: fmtcut = self._fmt.find('%(message)s') if 0 < fmtcut: indent = len(self._fmt[:fmtcut] % record.__dict__) indent = ' '*indent message = indent.join(message.splitlines(True)) return message if __name__ == '__main__': formatter = MyFormatter( '%(levelname)s %(asctime)s %(message)s', '%Y-%m-%d %H:%M:%S') handler = logging.StreamHandler() handler.setFormatter(formatter) assert not logging.root.handlers logging.root.addHandler(handler) logging.root.setLevel(logging.NOTSET) try: main() except Exception: logging.exception('Unhandled exception')
Отредактировано bw (Авг. 2, 2013 14:37:00)
Офлайн
Спасибо за наводку, слишком мало пользовался логингом, чтобы в дебри лезть.
Да и думал, что логинг имеет такую настройку.
Попробую твой вариант…
Отредактировано buddha (Авг. 2, 2013 15:37:01)
Офлайн