def createApplication(): appName = getAppConfig('app_name') apiServerIp = getAppConfig('api_server.bind_address') apiServerPort = int(getAppConfig('api_server.port')) games = getAppConfig('games').split(",") application = service.Application(name=appName) # log.msg(orderServerOption.get('nodaemon')) # log.msg(orderServerOption.keys()) # log.msg(orderServerOption.values()) # if orderServerOption.get('nodaemon') != 0: logDir = os.path.realpath(os.path.dirname(getAppConfig('logdir'))) logName = "%s.log" % ( appName, ) logFile = logfile.DailyLogFile(logName, logDir) #log.msg(logDir) application.setComponent(log.ILogObserver, log.FileLogObserver(logFile).emit) log.msg("load application: ", appName) log.msg("load games:", games) appSrv = service.IServiceCollection(application) _apiService = apiService(bindAddress=apiServerIp, port=apiServerPort, games=games) _apiService.setServiceParent(appSrv) _consumerService = consumerService(games=games) _consumerService.setServiceParent(appSrv) return application
def test_toDate(self): """ Test that L{DailyLogFile.toDate} converts its timestamp argument to a time tuple (year, month, day). """ log = logfile.DailyLogFile(self.name, self.dir) self.addCleanup(log.close) timestamp = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, 0)) self.assertEqual((2000, 1, 1), log.toDate(timestamp))
def test_rotatePermissionFileNotOk(self): """ L{DailyLogFile.rotate} doesn't do anything if the log file can't be written to. """ log = logfile.DailyLogFile(self.name, self.dir) self.addCleanup(log.close) os.chmod(log.path, 0o444) previousFile = log._file log.rotate() self.assertEqual(previousFile, log._file)
def test_toDateUsesArgumentsToMakeADate(self): """ Test that L{DailyLogFile.toDate} uses its arguments to create a new date. """ log = logfile.DailyLogFile(self.name, self.dir) self.addCleanup(log.close) date = (2014, 10, 22) seconds = time.mktime(date + (0, ) * 6) logDate = log.toDate(seconds) self.assertEqual(date, logDate)
def test_rotatePermissionDirectoryNotOk(self): """ L{DailyLogFile.rotate} doesn't do anything if the directory containing the log files can't be written to. """ log = logfile.DailyLogFile(self.name, self.dir) self.addCleanup(log.close) os.chmod(log.directory, 0o444) # Restore permissions so tests can be cleaned up. self.addCleanup(os.chmod, log.directory, 0o755) previousFile = log._file log.rotate() self.assertEqual(previousFile, log._file)
def start_logging(self): log_rotate = self.config['mark2.log.rotate_mode'] log_size = self.config['mark2.log.rotate_size'] log_limit = self.config['mark2.log.rotate_limit'] if log_rotate == 'daily': log_obj = logfile.DailyLogFile("%s.log" % self.server_name, self.shared_path) elif log_rotate in ('off', 'size'): log_obj = logfile.LogFile( "%s.log" % self.server_name, self.shared_path, rotateLength=log_size if log_rotate == 'size' else None, maxRotatedFiles=log_limit if log_limit != "" else None) else: raise ValueError("mark2.log.rotate-mode is invalid.") log.startLogging(log_obj)
def __init__(self, env, log_file): self.env = env if log_file: log_path = os.path.join(env.getInstancePath(), 'logs') # clear log files if env.config.getbool('seishub', 'clear_logs_on_startup'): log_base = os.path.splitext(log_file)[0] for file in iglob(os.path.join(log_path, log_base + '.*')): try: os.remove(file) except: pass # new log file daily_log_file = logfile.DailyLogFile(log_file, log_path) env.app.setComponent(log.ILogObserver, log.FileLogObserver(daily_log_file).emit) self.start()
def test_persistence(self): """ L{DailyLogFile} objects can be pickled and unpickled, which preserves all the various attributes of the log file. """ defaultMode = 0o642 log = logfile.DailyLogFile(self.name, self.dir, defaultMode) self.addCleanup(log.close) log.write("123") # Check that the unpickled log is the same as the original one. copy = pickle.loads(pickle.dumps(log)) self.addCleanup(copy.close) self.assertEqual(self.name, copy.name) self.assertEqual(self.dir, copy.directory) self.assertEqual(self.path, copy.path) self.assertEqual(defaultMode, copy.defaultMode) self.assertEqual(log.lastDate, copy.lastDate)
def open_stdout_logfile(self, log_file_fullpath): if self.__LOG_BUFFER__ != None: outpath = os.path.dirname(log_file_fullpath) outfile = os.path.basename(log_file_fullpath) from twisted.python import logfile from twisted.python import log as twisted_log class __TyFileLogObserver__(twisted_log.FileLogObserver): twisted_log.FileLogObserver.timeFormat = '%m-%d %H:%M:%S.%f' def emit(self, eventDict): eventDict['system'] = '-' twisted_log.FileLogObserver.emit(self, eventDict) logf = logfile.DailyLogFile(outfile, outpath) for line in self.__LOG_BUFFER__: logf.write(line) logf.write('\n') flo = __TyFileLogObserver__(logf) twisted_log.startLoggingWithObserver(flo.emit) self.__LOG_BUFFER__ = None
def test_toDateDefaultToday(self): """ Test that L{DailyLogFile.toDate} returns today's date by default. By mocking L{time.localtime}, we ensure that L{DailyLogFile.toDate} returns the first 3 values of L{time.localtime} which is the current date. Note that we don't compare the *real* result of L{DailyLogFile.toDate} to the *real* current date, as there's a slight possibility that the date changes between the 2 function calls. """ def mock_localtime(*args): self.assertEqual((), args) return list(range(0, 9)) log = logfile.DailyLogFile(self.name, self.dir) self.addCleanup(log.close) self.patch(time, "localtime", mock_localtime) logDate = log.toDate() self.assertEqual([0, 1, 2], logDate)
if path in self.watch_scheduler: self.watch_scheduler[path].reset(10) else: self.watch_scheduler[path] = reactor.callLater(10, self.eventFinished, path) def eventFinished(self, path): del self.watch_scheduler[path] self.addPack(path) def internalFileChanged(self, path): if not path.startswith(os.path.abspath(".")): return if path in self.internal_scheduler: self.internal_scheduler[path].reset(10) else: self.internal_scheduler[path] = reactor.callLater(10, self.internalFileFinished, path) def internalFileFinished(self, path): del self.internal_scheduler[path] if path == os.path.abspath("./txoffer.yaml"): self.updateConfig() # Launch the party application = service.Application("txoffer") applog = logfile.DailyLogFile("txoffer.log", ".") application.setComponent(log.ILogObserver, log.FileLogObserver(applog).emit) Master().setServiceParent(application)
from twisted.internet import reactor from twisted.python import log,logfile base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(base_dir) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cmdb_web.settings") import django django.setup() from cmdb.models import ac_cpu, ac_mem, ac_disk, ac_net from twisted.internet.protocol import ServerFactory from twisted.protocols import basic from twisted.application import service, internet BASE_LOG_DIR = os.path.join(base_dir, "log") f = logfile.DailyLogFile('service_agent.log', BASE_LOG_DIR) log.startLogging(f) class Mornitor_Protocol(basic.LineReceiver): def __init__(self): # pass def update(self,line): ''' 接受到json参数格式如下: { "hostname": "iZbp14xkfh6vkt9ane0gb8Z", "ip": "47.97.30.46",
from twisted.python import log, logfile from twisted.internet import reactor, task import random import time DELAYTIME = 2 def fun(): ret = random.random() * 2 log.msg("本次执行的结果是%s" % ret) return ret if __name__ == '__main__': log.startLogging(logfile.DailyLogFile("text.txt", './')) log.msg("text task started at {}".format(time.asctime())) task1 = task.LoopingCall(fun) task1.start(DELAYTIME) reactor.run()
# Author: chenweizhang # Date : 2019/9/20 import datetime import inspect import json import multiprocessing import os import platform import socket import subprocess import psutil from twisted.protocols import basic from twisted.internet import protocol, defer, task from twisted.application import service, internet from twisted.python import log, logfile f = logfile.DailyLogFile('agent.log', 'var/log/monitorAgent') log.startLogging(f) class InfoGather(object): def __init__(self): ''' 初始化信息,采集一些公用信息 ''' self.agent_data = dict() self.now_capture_time = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') ''' self.hostname = socket.gethostname() try:
else: log.FileLogObserver.emit(self, eventDict) class GeneralObserver(log.FileLogObserver): """ Logs messages from the apis """ def emit(self, eventDict): self.timeFormat = "%Y/%m/%d %H:%M:%S" if eventDict: if eventDict.get('log') == "general": log.FileLogObserver.emit(self, eventDict) log.startLoggingWithObserver( GeneralObserver( logfile.DailyLogFile("general-%s.log" % sys.argv[1], aztk_config.setup.get('paths', 'logs'))).emit, 0) log.startLoggingWithObserver( InternalFileLogObserver( logfile.DailyLogFile("twisted-%s.log" % sys.argv[1], aztk_config.setup.get('paths', 'logs'))).emit, 1) log.startLoggingWithObserver( FailureFileLogObserver( logfile.DailyLogFile("failures-%s.log" % sys.argv[1], aztk_config.setup.get('paths', 'logs'))).emit, 0) ############################### ## Generic Logging Interface ## ############################### class Logger: """