forked from kannibalox/PtpUploader
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Logger.py
44 lines (34 loc) · 1.39 KB
/
Logger.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
38
39
40
41
42
43
44
import codecs
import datetime
import sys
import traceback
# The reason for not using Python's logger:
# "While it might be tempting to create Logger instances on a per-connection basis, this is not a good idea because these instances are not garbage collected."
# http://docs.python.org/library/logging.html
class Logger:
def __init__(self, logFilePath):
self.LogFilePath = logFilePath;
def __Log(self, messageType, message, logException = False):
messageTime = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S" );
file = codecs.open( self.LogFilePath, "a", "utf-8" );
exceptionMessage = None
if logException:
exceptionMessage = traceback.format_exc( limit = None )
formattedMessage = None
if exceptionMessage is None:
formattedMessage = "[%s] %s %s" % ( messageTime, messageType, message )
else:
formattedMessage = "[%s] %s %s\n%s" % ( messageTime, messageType, message, exceptionMessage )
# To avoid "UnicodeEncodeError: 'ascii' codec can't encode character" errors...
print(formattedMessage.encode( sys.stdout.encoding, "ignore" ))
file.write( formattedMessage )
file.write( "\n" )
file.close()
def info(self, message):
self.__Log( "INFO", message )
def error(self, message):
self.__Log( "ERROR", message )
def exception(self, message):
self.__Log( "ERROR", message, logException = True )
def warning(self, message):
self.__Log( "WARNING", message )