import
os, sys
import
datetime
import
time
class
Mylog(
object
):
root_dir
=
sys.path[
0
]
root_path
=
sys.path[
0
]
+
os.path.sep
sys_sep
=
os.path.sep
option
=
{
'level'
:
0
,
'is_open'
:
True
,
'is_print'
:
True
,
'is_write'
:
True
,
'is_prefix'
:
True
,
'level_1_prefix'
:
'Test: '
,
'level_2_prefix'
:
'Warning: '
,
'level_3_prefix'
:
'Error: '
,
'root_dir_name'
:
'mylog'
,
'dir_name'
: ''
}
def
__init__(
self
, config
=
None
):
if
config
is
not
None
:
self
.option.update(
dict
(config))
save_dir
=
self
.root_path
+
self
.option[
'root_dir_name'
]
if
os.path.isdir(save_dir)
is
not
True
:
os.mkdir(save_dir)
if
len
(
self
.option[
'dir_name'
]) >
0
:
save_dir
+
=
self
.sys_sep
+
self
.option[
'dir_name'
]
if
os.path.isdir(save_dir)
is
not
True
:
os.mkdir(save_dir)
self
.save_dir
=
save_dir
self
.save_path
=
save_dir
+
self
.sys_sep
def
log(
self
, content
=
'', level
=
0
):
self
._print_log(content, level)
self
._write_log(content, level)
def
_print_log(
self
, content, level):
if
self
.option[
'is_open'
]
is
True
and
self
.option[
'is_print'
]
is
True
:
if
self
.option[
'level'
]
=
=
0
or
self
.option[
'level'
]
=
=
level:
if
level >
0
:
content
=
self
.option[
'level_'
+
str
(level)
+
'_prefix'
]
+
content
print
(content)
def
_write_log(
self
, content, level):
if
self
.option[
'is_open'
]
is
True
and
self
.option[
'is_print'
]
is
True
:
if
self
.option[
'level'
]
=
=
0
or
self
.option[
'level'
]
=
=
level:
if
self
.option[
'is_prefix'
]
is
True
:
today
=
datetime.date.today()
file_name
=
str
(today)
+
'.log'
now
=
time.strftime(
"%H:%M:%S"
)
log_file
=
self
.save_path
+
file_name
if
level >
0
:
content
=
self
.option[
'level_'
+
str
(level)
+
'_prefix'
]
+
content
if
os.path.isfile(log_file):
save_file
=
open
(log_file,
'a'
)
else
:
save_file
=
open
(log_file,
'w'
)
save_file.write(
str
(now)
+
"\r\n"
+
content
+
"\r\n"
)
save_file.close()
*
*
重点内容
__author__
=
'DiaoHuabin'
import
logging
import
getpass
import
sys
class
MyLog(
object
):
def
__init__(
self
):
user
=
getpass.getuser()
self
.logger
=
logging.getLogger(user)
self
.logger.setLevel(logging.DEBUG)
logFile
=
'./'
+
sys.argv[
1
][
0
:
-
3
]
+
'.log'
formatter
=
logging.Formatter(
'%(asctime)-12s $(levelname)-8s %(name)-10s %(message)-12s'
)
logHand
=
logging.FileHandler(logFile)
logHand.setFormatter(formatter)
logHand.setLevel(logging.ERROR)
logHandSt
=
logging.StreamHandler()
logHandSt.setFormatter(formatter)
self
.logger.addHandler(logHand)
self
.logger.addHandler(logHandSt)
def
debug(
self
,msg):
self
.logger.debug(msg)
def
info(
self
,msg):
self
.logger.info(msg)
def
warn(
self
,msg):
self
.logger.warn(msg)
def
error(
self
,msg):
self
.logger.error(msg)
def
critical(
self
,msg):
self
.logger.critical(msg)
if
__name__
=
=
'__main__'
:
mylogw
=
MyLog()
mylogw.debug(
"I'm debug"
)
mylogw.info(
"I'm info"
)
mylogw.warn(
"I'm warn"
)
mylogw.error(
"I'm error"
)
mylogw.critical(
"I'm critical"
)