-
Notifications
You must be signed in to change notification settings - Fork 64
/
customContext.py
37 lines (29 loc) · 1.15 KB
/
customContext.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from contextlib import contextmanager
from datetime import datetime
@contextmanager
def CustomLog(*args):
try:
myfile = open(*args)
myfile.write('############### Start Date: {} ###############\n'.format(datetime.now()))
yield myfile
finally:
myfile.write('############### End Date: {} ###############\n'.format(datetime.now()))
myfile.close()
with CustomLog('index.txt','a') as customfile:
customfile.write('THis is going to fail!\n')
customfile.write('THis is going to fail!\n')
customfile.write('THis is going to fail!\n')
customfile.write('THis is going to fail!\n')
class CustomLogger(object):
def __init__(self, file, mode):
self.mode = mode
self.file = file
def __enter__(self):
self.openfile = open(self.file,self.mode)
self.openfile.write('############### Start Date: {} ###############\n'.format(datetime.now()))
return self.openfile
def __exit__(self, *args):
self.openfile.write('############### End Date: {} ###############\n'.format(datetime.now()))
self.openfile.close()
with CustomLogger('CustomLoggerFromClass.txt','a') as fromclass:
fromclass.write('This is coming from class!\n')