Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ethen8181
GitHub Repository: ethen8181/machine-learning
Path: blob/master/python/decorators/log_timing.py
2577 views
1
import time
2
import logging
3
from functools import wraps
4
from importlib import reload
5
6
# http://stackoverflow.com/questions/18786912/get-output-from-the-logging-module-in-ipython-notebook
7
# ipython notebook already call basicConfig somewhere, thus reload the logging
8
reload(logging)
9
10
def logger(func):
11
"""
12
create logging for the function,
13
re-define the format to add specific logging time
14
"""
15
@wraps(func)
16
def wrapper( *args, **kwargs ):
17
logging.basicConfig( filename = '{}.log'.format( func.__name__ ),
18
format = '%(asctime)s -- %(levelname)s:%(name)s: %(message)s',
19
datefmt = '%Y/%m/%d-%H:%M:%S',
20
level = logging.INFO )
21
22
# custom the logging information
23
logging.info( 'Ran with args: {} and kwargs: {}'.format( args, kwargs ) )
24
return func( *args, **kwargs )
25
26
return wrapper
27
28
29
def timer(func):
30
"""time the running time of the passed in function"""
31
@wraps(func)
32
def wrapper( *args, **kwargs ):
33
t1 = time.time()
34
result = func( *args, **kwargs )
35
t2 = time.time() - t1
36
print( '{} ran in: {} sec'.format( func.__name__, t2 ) )
37
38
return wrapper
39
40
41
42