Created
February 2, 2012 14:39
-
-
Save huangdongxu/1723762 to your computer and use it in GitHub Desktop.
rlog.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import socket | |
import sys | |
import eventlet | |
import datetime | |
RLOG_PORT = 3726 | |
fds = {} | |
def output_to_file(channel, level, content): | |
global fds | |
dt = str(datetime.datetime.now()).split(' ')[0] | |
# check if log path exists | |
if os.path.exists('./' + channel) == False: | |
os.mkdir('./' + channel) | |
# check if the log file opened | |
filename = './' + channel + '/' + dt + '.log' | |
if filename not in fds.keys(): | |
fp = open(filename, 'a') | |
fds[filename] = fp | |
fp = fds[filename] | |
s = '%s channel:%s level:%s content:%s' % (str(datetime.datetime.now()), channel, level , content) | |
fp.write(s) | |
fp.flush() | |
def output(channel, level, content): | |
s = "%s@\033[1;33;40m%s\033[0m [\033[1;31;40m%s\033[0m] %s" % (str(datetime.datetime.now()),channel, level, content) | |
print s | |
def rlog_handler(sock): | |
log = sock.makefile('r').readline() | |
if len(log.split('|')) < 3 : | |
print 'invalid log format.' | |
sock.close() | |
return | |
channel = log.split('|')[0] | |
level = log.split('|')[1] | |
content = '|'.join(log.split('|')[2:]) | |
output(channel, level, content) | |
output_to_file(channel, level, content) | |
sock.close() | |
if __name__ == '__main__': | |
if len(sys.argv) == 2 : | |
RLOG_PORT = int(sys.argv[1]) | |
print 'RLogger running on port', RLOG_PORT | |
server = eventlet.listen(('0.0.0.0', RLOG_PORT)) | |
pool = eventlet.GreenPool() | |
while True: | |
try: | |
new_sock, address = server.accept() | |
pool.spawn_n(rlog_handler, new_sock) | |
except (SystemExit, KeyboardInterrupt): | |
print 'do some cleaning...' | |
for filename in fds.keys(): | |
fds[filename].close() | |
break; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment