logging Python

Содержание
Введение
Включить Debug
Лог в файл
Форматирование
Похожие статьи

Введение

По умолчанию Info и Debug отключены

import logging logging.critical("Critial Log") logging.error("Error Log") logging.warning("Warning Log") logging.info("Info Log") logging.debug("Debug Log")

python log_example.py

CRITICAL:root:Critial Log ERROR:root:Error Log WARNING:root:Warning Log

Включить Debug

import logging logging.basicConfig(level=logging.DEBUG) logging.critical("Critial Log") logging.error("Error Log") logging.warning("Warning Log") logging.info("Info Log") logging.debug("Debug Log")

python log_example.py

CRITICAL:root:Critial Log ERROR:root:Error Log WARNING:root:Warning Log INFO:root:Info Log DEBUG:root:Debug Log

Лог в файл

import logging logging.basicConfig(filename='example.log', level=logging.DEBUG) logging.critical("Critial Log") logging.error("Error Log") logging.warning("Warning Log") logging.info("Info Log") logging.debug("Debug Log")

python log_example.py

В терминал уже ничего не выводится, зато появился файл example.log

cat example.log

CRITICAL:root:Critial Log ERROR:root:Error Log WARNING:root:Warning Log INFO:root:Info Log DEBUG:root:Debug Log

Форматирование

Можно задать нужный вам формат логов с помощью logrecord-attributes

import logging logging.basicConfig(filename='example.log', level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(message)s') logging.critical("Critial Log") logging.error("Error Log") logging.warning("Warning Log") logging.info("Info Log") logging.debug("Debug Log")

python log_example.py
cat example.log

2026-10-12 15:21:43,280:CRITICAL:Critial Log 2026-10-12 15:21:43,280:ERROR:Error Log 2026-10-12 15:21:43,280:WARNING:Warning Log 2026-10-12 15:21:43,280:INFO:Info Log 2026-10-12 15:21:43,280:DEBUG:Debug Log

Article author: Andrei Olegovich

Похожие статьи
Python
Интерактивный режим
dict, list, str …
\: перенос строки
if, elif, else
Циклы
Функции
try except
Пакеты
ООП
Опеределить тип переменной Python
Работа с REST API на Python
Файлы: записать, прочитать…
Работа с базами данных
datetime: Дата и время в Python
json.dumps
Сложности при работе с Python
Фреймворки: Django, Flask
socket: Python Sockets
Виртуальное окружение
subprocess: bash команды из Python
multiprocessing: несколько процессов одновременно
psutil: cистемные ресурсы
sys.argv: аргументы командной строки
PyCharm: IDE
pydantic: валидация данных
paramiko: SSH из Python
Обучение Python

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: