Python Forum
Logging a function - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Logging a function (/thread-2869.html)



Logging a function - harrington40 - Apr-16-2017

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



RE: Logging a function - Mekire - Apr-17-2017

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/


RE: Logging a function - snippsat - Apr-17-2017

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.



RE: Logging a function - volcano63 - Apr-17-2017

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'
>>>