How do I log when a function is called using counter and python logging? - Stack Overflow

admin2025-04-16  3

I'm trying to log every time the function "Hello" finds 1.png. Is there a way to do this using counter or some other method, it would then log it into "anomaly.log" using logging, is there a way to do this?

    import logging
    import pyautogui
    import schedule
    import time
    
    
    def logger():
        logging.basicConfig(level=logging.INFO, filename="bandit.log", filemode="w", format="%(asctime)s - %(levelname)s - %(message)s")
        logger = logging.getLogger(__name__)
        logger.propagate = False
    
        handler = logging.FileHandler('anomaly.log')
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        handler.setFormatter(formatter)
    
        logger.addHandler(handler)
        logger.info('test')
    
    def hello():
        try:
            pyautogui.locateOnScreen('1.png', confidence=0.9)
        except pyautogui.ImageNotFoundException:
            pass
        if pyautogui.locateOnScreen('1.png', confidence=0.9):
            hello.counter += 1
            logging.info(hello.counter)
    hello.counter = 0

    # schedule for main working code
    schedule.every(1).seconds.do(logger)
    
    # schedule for main working code
    schedule.every(1).seconds.do(hello)

while True:
    schedule.run_pending()
    time.sleep(1)

I'm trying to log every time the function "Hello" finds 1.png. Is there a way to do this using counter or some other method, it would then log it into "anomaly.log" using logging, is there a way to do this?

    import logging
    import pyautogui
    import schedule
    import time
    
    
    def logger():
        logging.basicConfig(level=logging.INFO, filename="bandit.log", filemode="w", format="%(asctime)s - %(levelname)s - %(message)s")
        logger = logging.getLogger(__name__)
        logger.propagate = False
    
        handler = logging.FileHandler('anomaly.log')
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        handler.setFormatter(formatter)
    
        logger.addHandler(handler)
        logger.info('test')
    
    def hello():
        try:
            pyautogui.locateOnScreen('1.png', confidence=0.9)
        except pyautogui.ImageNotFoundException:
            pass
        if pyautogui.locateOnScreen('1.png', confidence=0.9):
            hello.counter += 1
            logging.info(hello.counter)
    hello.counter = 0

    # schedule for main working code
    schedule.every(1).seconds.do(logger)
    
    # schedule for main working code
    schedule.every(1).seconds.do(hello)

while True:
    schedule.run_pending()
    time.sleep(1)
Share Improve this question edited Feb 2 at 18:28 D3AD_SHOT asked Feb 2 at 18:19 D3AD_SHOTD3AD_SHOT 336 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 0

I figured a part of it out, now i just need to figure out how to log it using logging.info, if anybody has any ideas I'd appreciate it, thanks

call_count = 0


def my_function():
    try:
        location = pyautogui.locateOnScreen('1.png', confidence=0.9)
        if pyautogui.locateOnScreen('1.png', confidence=0.9):
            global call_count
            call_count += 1
            print(call_count)
    except pyautogui.ImageNotFoundException:
        pass

Figured it out, hope this helps anyone in the future who may have the same issues.

def logger():
    logging.basicConfig(level=logging.INFO, filename="bandit.log", filemode="w", format="%(asctime)s - %(levelname)s - %(message)s")
    logger = logging.getLogger(__name__)
    logger.propagate = False

    handler = logging.FileHandler('anomaly.log')
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    handler.setFormatter(formatter)

    logger.addHandler(handler)
    try:
        location = pyautogui.locateOnScreen('1.png', confidence=0.9)
        if pyautogui.locateOnScreen('1.png', confidence=0.9):
            global call_count
            call_count += 1
            logger.info(call_count)
    except pyautogui.ImageNotFoundException:
        pass

There are two issues with your code.

1. variable name and scope:

Your counter variable name, hello.counter, is wrong. Python variable names should only contain alphanumerical and underscore characters.

Rules for Python variables (link):

  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive (age, Age and AGE are three different variables)
  • A variable name cannot be any of the Python keywords.

Because of the way python's scope resolution, hellocounter += 1 raises UnboundLocalError. You seemed to have get around this issue by using global keyword

2. Main issue

Inside your hello() function, you are using logging not the logger object. As a result it logs messages to only "bandit.log", not 'anomaly.log' file.

def hello():
        try:
            pyautogui.locateOnScreen('1.png', confidence=0.9)
        except pyautogui.ImageNotFoundException:
            pass
        if pyautogui.locateOnScreen('1.png', confidence=0.9):
            hello.counter += 1
            logging.info(hello.counter) #<------------------

You should use logger instead. But to be able to use logger, it should be accessible within hello function.

So, either pass the logger object as an argument to hello function, or declare logger as a global variable. Second approach is better, since other functions can use it too easily.

Note: based on your code, you don't have to call logging configuration function, logger , every second. Just call it once. Also, it is always good practice to give descriptive name to functions and variables.

import logging
import pyautogui
import schedule
import time


def logger_config():  # <------------- descriptive function name
    logging.basicConfig(level=logging.INFO, filename="bandit.log", filemode="w", format="%(asctime)s - %(levelname)s - %(message)s")
    logger = logging.getLogger(__name__)
    logger.propagate = False

    handler = logging.FileHandler('anomaly.log')
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger #<------------ return logger object

# configure logging
logger = logger_config()  # <-------------- declare global variable logger

call_count = 0
def hello():
    try:
        location = pyautogui.locateOnScreen("1.png", confidence=0.9)
        if pyautogui.locateOnScreen("1.png", confidence=0.9):
            global call_count
            call_count += 1
            logger.info(call_count)
    except pyautogui.ImageNotFoundException:
        pass

# schedule for main working code
# schedule.every(1).seconds.do(logger_config)  # <---------- No need to call every second

# schedule for main working code
schedule.every(1).seconds.do(hello)

while True:
    schedule.run_pending()
    time.sleep(1)
转载请注明原文地址:http://anycun.com/QandA/1744791817a87680.html