D3AD_SHOT
D3AD_SHOT

Reputation: 33

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

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)

Upvotes: 0

Views: 27

Answers (2)

D3AD_SHOT
D3AD_SHOT

Reputation: 33

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

Upvotes: 0

D3AD_SHOT
D3AD_SHOT

Reputation: 33

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

Upvotes: 0

Related Questions