Python의 오류 처리 및 로깅

PHPz
풀어 주다: 2024-08-13 06:40:03
원래의
686명이 탐색했습니다.

소프트웨어 작성은 완벽과는 거리가 먼 활동입니다. 아이디어 구상부터 제작까지 오류가 나타날 수도 있고, 고의로 실패하는 경우도 있습니다. 이것이 기본 프로그래밍 언어로 오류 처리 및 로그인을 이해하는 것이 숙달해야 할 중요한 기술인 이유입니다.

오류는 발생할 수 있고 상황이 발생할 수 있지만, 오류에 대한 준비와 정보를 바탕으로 대응하는 방식을 통해 최대한 빨리 상황에서 벗어날 수 있습니다.

이 글에서는 Python의 오류 처리 및 로그인에 대해 알아봅니다. 주로 예외 사항과 Python의 로깅 패키지를 사용하여 다양한 유형의 로그를 작성하는 방법을 살펴보겠습니다.

이와 같은 주제를 다루는 더 많은 콘텐츠에 관심이 있다면 제 뉴스레터 를 구독하여 소프트웨어 프로그래밍, 아키텍처 및 아키텍처에 대한 정기적인 업데이트를 받아보세요. 기술 관련 통찰력.

Python의 예외

다른 많은 프로그래밍 언어와 마찬가지로 Python에는 오류가 발생할 때 예외를 발생시키는 기능이 있습니다. 프로그래밍에서 예외는 프로그램 실행 중에 발생하여 명령의 정상적인 흐름을 방해하는 이벤트입니다.

Python에서 예외는 실행 중에 감지된 오류입니다. 예외가 발생하면 Python은 코드 실행을 중지하고 오류를 처리할 특수 코드 블록(try/exc 블록)을 찾습니다.

다음은 Python 프로그램에서 발생할 수 있는 몇 가지 일반적인 예외입니다.

  • ZeroDivisionError: 숫자를 0으로 나누려고 할 때 발생합니다.

  • FileNotFoundError: 존재하지 않는 파일을 열려고 할 때 발생합니다.

  • ValueError: 문자열이 숫자를 나타내지 않는 경우 문자열을 정수로 변환하려고 하면 발생합니다.

  • IndexError: 존재하지 않는 인덱스가 있는 목록에서 요소를 검색하려고 할 때 발생합니다.

더 많은 예외가 있으며 Python에서는 사용자 정의 동작이 필요한 경우 고유한 예외를 생성할 수 있는 기능을 제공합니다. 이는 기사 뒷부분에서 살펴볼 기능입니다.

Python 예외를 처리하려면 예외를 포착해야 합니다. 예외를 포착하려면 try/Exception이라는 간단한 구문이 필요합니다. 이에 대해 살펴보겠습니다.

시도/제외

try/exc 블록은 예외를 처리하는 데 사용됩니다. 예외가 발생할 수 있는 코드는 try 블록에 배치되고, 예외가 발생하면 Except 블록이 실행됩니다. 코드 블록의 try/제외 구문은 다음과 같습니다.

try:
    # Code that might raise an exception
    pass
except ExceptionType as e:
    # Code to handle the exception
    pass
로그인 후 복사

실패할 가능성이 있는 코드는 try 블록 안에 넣습니다. 문제가 발생하면 프로그램 실행이 제외 블록에 들어갑니다.

다음은 try/제외 작동 방식을 보여주는 순서도입니다.

Error Handling and Logging in Python

이 접근 방식을 사용하여 0으로 나누기를 어떻게 처리할 수 있는지 살펴보겠습니다.

# Handling division by zero
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")
# The code will continue its execution
로그인 후 복사

try/제외 구문에는 else 및 finally와 같은 추가 블록도 있습니다.

try:
    # Code that might raise an exception
    pass
except ExceptionType as e:
    # Code to handle the exception
    pass
else:
    # Code to run if no exception is raised
    pass
finally:
    # Code that always runs, regardless of whether an exception was raised or not
    pass
로그인 후 복사

이러한 블록은 선택 사항이지만 특정 용도로 사용됩니다.

  • else 블록(선택 사항): try 블록에서 예외가 발생하지 않은 경우 실행되는 코드를 포함합니다. try 블록이 성공한 경우에만 실행해야 하는 코드에 유용합니다.

  • finally Block(선택 사항): 예외 발생 여부에 관계없이 항상 실행되는 코드를 포함합니다. 이는 일반적으로 파일 닫기 또는 리소스 해제와 같은 정리 작업에 사용됩니다.

다음은 오류가 발생한 경우 최종적으로 파일 닫기를 처리하는 예입니다.

try:
    # Open the file
    file = open('example.txt', 'r')

    # Read from the file
    content = file.read()

    # Print file content (this will only execute if no exceptions are raised)
    print(content)
except FileNotFoundError as e:
    # Handle the specific exception
    print(f"Error: {e}")
except Exception as e:
    # Handle any other exceptions
    print(f"An unexpected error occurred: {e}")
else:
    # Code that runs if no exception was raised in the try block
    print("File read successfully.")
finally:
    # Ensure the file is closed, regardless of whether an exception was raised
    try:
        file.close()
        print("File closed.")
    except:
        # Handle the case where file was never opened (e.g., if open() failed)
        print("File was not opened or already closed.")
로그인 후 복사

면책조항: 위의 예에서는 오류가 발생하더라도 파일이 제대로 닫히도록 try/excess/finally를 사용하여 파일을 처리하는 방법을 보여줍니다. 그러나 이 접근 방식은 일상적인 파일 작업에는 적합하지 않습니다. 실제로 Python에서 파일을 처리하려면 with 문을 사용하는 것이 좋습니다. with 문은 파일 열기 및 닫기를 자동으로 관리하여 예외가 발생하더라도 해당 제품군이 완료된 후 파일이 제대로 닫히도록 보장합니다.

이것이 try/Exception이 작동하는 방식입니다. 이제 if/else와 혼동될 수 있습니다. 언제 try/Exception을 사용해야 하며, 언제 if/else를 사용해야 합니까?

try/제외와 if/else의 차이점은 무엇인가요? 오류가 발생하기 전에 예측하고 처리할 수 있는 조건을 확인하고 싶을 때는 if/else를 사용하고, 특히 쉽게 예상할 수 없는 오류의 경우 코드 실행 중에 발생하는 예외를 포착하고 관리하려면 try/Exception을 사용하세요.

아래의 경우 if/else가 제대로 작동하지 않습니다.

filename = 'non_existent_file.txt'

if filename:  # This only checks if filename is not empty, not if the file exists
    # The following line will raise an exception if the file doesn't exist
    content = open(filename, 'r').read()  # This will crash if the file does not exist
    if content:
        print("File content exists:")
        print(content)
    else:
        print("File is empty.")
else:
    print("Filename is invalid.")
로그인 후 복사

시도/제외를 사용하는 더 나은 솔루션은 다음과 같습니다.

filename = 'non_existent_file.txt'

try:
    content = open(filename, 'r').read()
    if content:
        print("File content exists:")
        print(content)
    else:
        print("File is empty.")
except FileNotFoundError:
    print("Error: File not found.")
로그인 후 복사

In the solution above, the code attempts to open and read a file, checking if its content exists and printing it if present. If the file does not exist, it catches the FileNotFoundError and prints an error message, preventing the program from crashing.

As mentioned earlier in the article, Python allows for custom exceptions. Let’s learn more about it.

Creating Custom Exceptions in Python

In Python, you can define your own exceptions to handle specific error conditions in a more granular way. Custom exceptions are particularly useful in complex applications, such as fintech, where you may need to enforce business rules or handle specific error cases uniquely.

For example, in a fintech application, you might have a scenario where a wallet’s balance is checked against certain criteria. You may want to raise an exception if a wallet’s balance is not sufficient or does not conform to specific rules. Here’s how you can create and use a custom exception for this purpose:

# Define a custom exception
class WalletBalanceError(Exception):
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

# Function that checks wallet balance
def check_wallet_balance(wallet_balance, required_balance):
    if wallet_balance < required_balance:
        # Raise the custom exception with a specific message
        raise WalletBalanceError(f"Insufficient balance: Wallet balance of {wallet_balance} is less than the required {required_balance}.")

# Example usage
try:
    # Example wallet balance and required balance
    wallet_balance = 50
    required_balance = 100

    # Check if the wallet balance is sufficient
    check_wallet_balance(wallet_balance, required_balance)
except WalletBalanceError as e:
    # Handle the custom exception
    print(f"Error: {e}")
로그인 후 복사

In this example, we define a custom exception WalletBalanceError to handle cases where a wallet’s balance does not meet the required criteria. The check_wallet_balance function raises this exception if the wallet’s balance is insufficient, providing a clear and specific error message.

Custom exceptions in Python help make the code more readable and maintainable by clearly defining specific error conditions and handling them in a structured manner.

Now that we know how to handle errors in Python, it’s time to understand what to do when these errors occur. There are many strategies, but keeping a log of these errors can help identify issues later and correct them. In the next section of this article, we will explore logging.

Logging in Python

Logging helps developers track errors, events, or any runtime information in an application or program. Logging is an important and crucial aspect of software engineering as it has the ability to record everything that goes right or wrong in a post-development application. Logging is one of the most important pillars of monitoring.

Python provides a built-in module that can be used for logging

purposes. To use this module, the first thing to do is to import it.

import logging
로그인 후 복사

Then, configure the logger using the basicConfig method. You need to pass parameters to it, such as the log level, the format of the message, and the output file to save the log.

import logging

# Set up the basic configuration for logging
logging.basicConfig(filename='app.log', level=logging.DEBUG,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# Log messages of various severity levels
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')
로그인 후 복사

In the example above, logs will be written to a file called app.log. The log message format includes the timestamp, logger name, log level, and the actual message.

Python logging has different log levels that indicate the severity of an event or message. These log levels allow you to categorize and filter messages based on their importance. Here’s a breakdown of the common log levels in Python:

Log Levels

  1. DEBUG: Detailed information, typically of interest only when diagnosing problems. Used for debugging purposes during development.

  2. INFO: Confirmation that things are working as expected. This is the level you would use for normal operations and informational messages.

  3. WARNING: An indication that something unexpected happened, or indicative of some problem in the near future (e.g., "disk space low"). The software is still working as expected.

  4. ERROR: Due to a more serious problem, the software has not been able to perform some function. An error indicates a significant issue that needs attention.

  5. CRITICAL: A very serious error, indicating that the program itself may be unable to continue running. Critical errors often represent severe problems that require immediate action.

The logging module allows you to control which messages are recorded by setting the logging level. Only messages that are equal to or more severe than the set level will be logged. The default level is WARNING, meaning only WARNING, ERROR, and CRITICAL messages are logged unless you change the logging configuration.

In the code example above, we set the logging level to DEBUG, which means all log messages (DEBUG, INFO, WARNING, ERROR, and CRITICAL) will be recorded in the app.log file.

You can also create custom loggers, which give you more control over how messages are logged. Custom loggers allow you to set up multiple loggers with different configurations, such as different log levels, formats, or output destinations. This is particularly useful in larger applications where you need to separate logs for different modules or components.

Here’s how you can create and use a custom logger:

import logging

# Create a custom logger
logger = logging.getLogger('my_custom_logger')

# Set the log level for the custom logger
logger.setLevel(logging.DEBUG)

# Create a file handler to write logs to a file
file_handler = logging.FileHandler('custom.log')

# Create a console handler to output logs to the console
console_handler = logging.StreamHandler()

# Set log levels for the handlers
file_handler.setLevel(logging.ERROR)
console_handler.setLevel(logging.DEBUG)

# Create a formatter for log messages
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# Add the formatter to the handlers
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)

# Add the handlers to the logger
logger.addHandler(file_handler)
logger.addHandler(console_handler)

# Log messages using the custom logger
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')
로그인 후 복사

In this example, we create a custom logger named my_custom_logger. This logger writes ERROR and more severe messages to a file called custom.log, while DEBUG and more severe messages are output to the console. By customizing the loggers, you can tailor the logging behavior to fit the specific needs of your application.

Real-world Example: Logging in a Web Application

In a web application, logging plays a critical role in monitoring and maintaining the system’s health. For example, in a Flask web application, you might use logging to track incoming requests, errors, and performance metrics.

Here’s a basic example of how you can use logging in a Flask application:

from flask import Flask, request
import logging

app = Flask(__name__)

# Set up the basic configuration for logging
logging.basicConfig(filename='webapp.log', level=logging.INFO,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

@app.route('/')
def index():
    app.logger.info('Index page accessed')
    return 'Welcome to the Flask Web Application!'

@app.route('/error')
def error():
    app.logger.error('Error page accessed')
    raise ValueError('This is a simulated error')

if __name__ == '__main__':
    app.run(debug=True)
로그인 후 복사

In this Flask application, we configure logging to write logs to a file named webapp.log. Each time the index page is accessed, an informational log message is recorded. If the error page is accessed, an error log message is recorded, and a simulated error is raised.

By implementing logging in your web application, you can gain insights into user activity, system errors, and performance issues. This information is invaluable for debugging, troubleshooting, and optimizing the application.

Conclusion

Error handling and logging are essential aspects of software development, ensuring that applications run smoothly and that any issues are quickly identified and resolved.

In this article, we explored exceptions in Python, including how to handle them using try/except, and the importance of logging for tracking errors and events. We also discussed how to create custom exceptions and custom loggers to suit specific application needs.

By mastering error handling and logging, you’ll be better equipped to build robust and maintainable software that can gracefully handle unexpected situations and provide valuable insights into its operation.

If you enjoyed this article, consider subscribing to my newsletter so you don't miss out on future updates.

Your feedback is valuable! If you have any suggestions, critiques, or questions, please leave a comment below.

위 내용은 Python의 오류 처리 및 로깅의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!