לדלג לתוכן

6.6 לוגים הרצאה

קונספט - לוגים

  • לוגים זה מידע שנשמר על התוכנה בזמן שהיא רצה
  • הרבה פעמים כשאנחנו מפתחים תוכנה, אנחנו רוצים לשמור "לוגים" על התוכנה בזמן שהיא רצה
  • כמו שאנחנו יכולים לשמור לוגים, אנחנו גם בדרך כלל נציג אותם בזמן שהתוכנה רצה.
  • מדוע לוגים כאלה חשובים כשמפתחים תוכנה גדולה?
    • כשמוציאים תוכנה גדולה, אנחנו רוצים שיהיו לוגים לתוכנה כדי שיהיה לנו קל יותר לדבג, למצוא באגים ואפילו למצוא האקרים שמנסים לפרוץ לנו את התוכנה.
    • בכל תוכנה גדולה שמכבדת את עצמה יש לוגים

לוגים בפייתון

  • המודול המובנה logging
    import logging
    
    # Log messages at different 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.")
    
  • יש המון סוגים של לוגים, לכל לוג יש איזשהו סוג - level, זה יכול להיות לוג של debug, info, warning, error, critical

  • אפשר לשנות את ההתנהגות של הלוגים באמצעות הפונקציה הבאה:

    logging.basicConfig(
        level=logging.DEBUG,  # Set the logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
        format='%(asctime)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler('app.log'),  # Log to a file
            logging.StreamHandler()          # Log to the console
        ]
    )
    

  • כך אפשר להגדיר לאיזה קובץ הלוגים ישמרו, האם להציג בפלט התוכנה את הלוגים, איך הלוגים אמורים להראות, ומה הסוג לוגים הדיפולטי

איפה נשתמש בלוגים?

  • בexception handling
    try:
        result = 10 / 0
    except Exception as e:
        logging.error("An error occurred: %s", str(e), exc_info=True)
    
  • כאשר אנחנו רוצים לשמור מידע כלשהו שקשור לתוכנה
    import logging
    
    def process_data(data):
        logging.info(f"Processing data: {data}")
        # Actual data processing logic goes here
    
    # Example usage
    data_to_process = [1, 2, 3, 4, 5]
    process_data(data_to_process)
    
  • כאשר אנחנו רוצים לשמור event-ים שקורים בתוכנה
    import logging
    
    def track_event(event_name, details):
        logging.info("Event: %s - Details: %s", event_name, details)
    
    def login(username, password)
        track_event("User Login", {username: password})
        do_login(username, password)
    
    login(input("Enter Username: "), input("Enter Password: "))