Python Logging Implementation > Python

Entire search within the site

Python

Python Logging Implementation

Page Info

Content

Python Logging Implementation

In Python, the built-in logging module allows you to track events that occur during program execution. Logging is more flexible than print() statements because it provides log levels, formatting, and the ability to write logs to files.

Basic Logging Example


import logging

# Configure basic logging
logging.basicConfig(level=logging.INFO)

# Example log messages
logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")
logging.critical("This is a critical message")
  

Explanation:

  • logging.basicConfig(level=logging.INFO): Sets the logging level (INFO and above are displayed).
  • Different log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.

Logging to a File


import logging

# Configure logging to write to a file
logging.basicConfig(
    filename='app.log', 
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

logging.info("Program started")
logging.warning("This is a warning")
logging.error("An error occurred")
  

Explanation:

  • filename='app.log': Logs are saved to app.log instead of the console.
  • format='%(asctime)s - %(levelname)s - %(message)s': Custom format including timestamp, log level, and message.

Advanced Logging with Multiple Levels


import logging

# Create a logger object
logger = logging.getLogger("my_logger")
logger.setLevel(logging.DEBUG)

# Create console handler
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)

# Create formatter and add to handler
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)

# Add handler to logger
logger.addHandler(ch)

# Example messages
logger.debug("Debug message")     # Won't appear in console
logger.info("Info message")       # Won't appear in console
logger.warning("Warning message") # Will appear
logger.error("Error message")     # Will appear
  

Key Points

  • Flexible log levels: Control the verbosity of your logs with DEBUG, INFO, WARNING, ERROR, and CRITICAL.
  • Logging output: Logs can be written to console, files, or both.
  • Formatting: Include timestamps, logger names, and log levels for better traceability.
  • Better than print(): Logging is non-intrusive and can be easily disabled or redirected.

SEO Keywords

Python logging example, Python log to file, Python logger, Python logging levels, Python debug info warning error, Python logging configuration

Use Python's logging module to track program execution, handle debugging information, and save logs for later analysis efficiently and flexibly.

Good0 Bad0

댓글목록

등록된 댓글이 없습니다.

Python

Latest Posts

Total 31 posts | Page 1
Python List
num Title Author-data
31 Python Regular Expressions (RegEx) Basic Matching view : 11 New no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29
11
30 Python Timer and Time Measurement (time module) view : 8 New no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29
8
29 Python Iterators (Iterator Usage) view : 6 New no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29
6
28 Python Inheritance (OOP) view : 4 New no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29
4
27 Python Classes and Object Creation (OOP) view : 7 New no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29
7
26 Python Dictionary Sorting (By Key / By Value) view : 4 New no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29
4
25 Python Logging Implementation view : 4 New no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29
4
24 Python Exception Handling (try-except) view : 4 New no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29
4
23 Python CSV File Reading and Processing view : 5 New no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29
5
22 Python JSON Data Handling (Read/Write) view : 5 New no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29
5
21 Python File Reading and Writing (Text Files) view : 3 New no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29
3
20 Python Decorators: Implementation and Usage view : 9 New no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29
9
19 Python Generators: Implementation and Usage view : 5 New no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29
5
18 Python Lambda Functions view : 8 New no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29
8
17 Python Remove Duplicate Elements from a List view : 10 New no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29
10

visit

today
52
yesday
144
maxday
144
allday
196
Copyright © https://goposu.com/g All rights reserved.