Python Forum
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Logging a function
#1
Hello, thanks for reading.
I have look at different logging module and examples which demonstrate python's logging examples.
 One questions that remains  is how does one logged a simple function  in a file. for example
 def Add(x,y):
  return( x + y)
 Any idea or a good tutorials that shows how to go about would be appreciated.

my code here
Reply
#2
Pymotw is a good site when trying to learn a new module.
Read through this and see if it gets you going where you want to go:
https://pymotw.com/3/logging/
Reply
#3
So a setup like this,we get a lot of info.
import my_log

def add(x, y):
   try:
       return(x + y)
   except Exception as error:
       my_log.logger.exception('msg')

if __name__ == '__main__':
   my_log.logger.info('Start')
   value = add(33, 50)
   my_log.logger.debug(value)
   my_log.logger.info('Finish')
   print(value)
After two run in logg file,second run with add(5, '50').
Output:
2017-04-17 13:05:53,512 - my_log - INFO - Start 2017-04-17 13:05:53,513 - my_log - DEBUG - 83 2017-04-17 13:05:53,513 - my_log - INFO - Finish 2017-04-17 13:06:36,155 - my_log - INFO - Start 2017-04-17 13:06:36,156 - my_log - ERROR - msg Traceback (most recent call last):   File "log6.py", line 5, in add     return(x + y) TypeError: unsupported operand type(s) for +: 'int' and 'str' 2017-04-17 13:06:36,156 - my_log - DEBUG - None 2017-04-17 13:06:36,156 - my_log - INFO - Finish
I import my_log where the setup is.
Reply
#4
If you are looking for a scalable way to log function calls - I would suggest a  decorator in that style

import logging

from functools import wraps
logging.basicConfig(level=logging.DEBUG)

def logging_wrapper(func):
    @wraps(func)
    def logging_inner(*args, **kwargs):
        kwargs_formatted = ['{}={}'.format(k, repr(v)) for k, v in kwargs.items()]
        call_line = 'Func call: {}({})'.format(func.__name__, 
                                    ', '.join([repr(v) for v in args] + kwargs_formatted))
        try:
            res = func(*args, **kwargs)
            logging.debug('{} - returns {}'.format(call_line, repr(res)))
            return res
        except Exception as exc:
            logging.exception(call_line + ' caused exception!')
    return logging_inner
             
Now, decorate function of your choice
@logging_wrapper
def add(x, y):
    return x + y
Shall we test?  
>>> add(1, 4)
DEBUG:root:Func call: add(1, 4) - returns 5
5
>>> add(1, '4')
ERROR:root:Func call: add(1, '4') caused exception!
Traceback (most recent call last):
  File "<stdin>", line 8, in logging_inner
  File "<stdin>", line 3, in add
TypeError: unsupported operand type(s) for +: 'int' and 'str'
But what about named arguments?
>>> @logging_wrapper
... def add(first, second=None):
...     return first + second
...
>>> add(1,4)
DEBUG:root:Func call: add(1, 4) - returns 5
5
>>> add(1, second=4)
DEBUG:root:Func call: add(1, second=4) - returns 5
5
>>> add(1, second='4')
ERROR:root:Func call: add(1, second='4') caused exception!
Traceback (most recent call last):
  File "<stdin>", line 8, in logging_inner
  File "<stdin>", line 3, in add
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020