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
Title-Author-data
Python Regular Expressions (RegEx) Basic Matching 12
no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Timer and Time Measurement (time module) 9
no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Iterators (Iterator Usage) 10
no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Inheritance (OOP) 5
no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Classes and Object Creation (OOP) 8
no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Dictionary Sorting (By Key / By Value) 5
no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Logging Implementation 5
no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Exception Handling (try-except) 8
no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python CSV File Reading and Processing 7
no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python JSON Data Handling (Read/Write) 6
no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python File Reading and Writing (Text Files) 4
no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Decorators: Implementation and Usage 11
no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Generators: Implementation and Usage 7
no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Lambda Functions 9
no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Remove Duplicate Elements from a List 11
no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New

visit

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