【问题标题】:How to logging to different log files by using for loop in python如何在python中使用for循环记录到不同的日志文件
【发布时间】:2022-07-21 14:22:11
【问题描述】:

我正在编写 python 脚本,它使用 paramiko 建立 ssh 连接,并接收在不同 NE 上执行的不同命令的响应,并将每个 NE 的日志写入不同的日志文件中。我正在使用下面的代码,其中我定义了记录器主函数并将日志写入同一类中的其他函数。编写单个日志文件时工作正常。请告诉我如何为不同的NE编写不同的日志文件。

代码:

def main(self):
    
    global logger
        
    with open(self.hostfile, 'r') as ip:
        ip_list = ip.read().splitlines()
        for host in ip_list:
            filename = "connection_debug-{0}.log".format(host)
            print('filename is:', filename)
            logging.basicConfig(filename=filename,
                                format='%(asctime)s %(message)s',
                                filemode='w')
            logger = logging.getLogger()
            logger.setLevel(logging.DEBUG)
                    
                    
def send_to_ne(self, command, prompt):
        channel.send('%s \n' % command)
        while not channel.recv_ready():
            time.sleep(2)
        #self.get_channel_ready()
        global response
        response = " "
        while not response.endswith(prompt):
            received_result = channel.recv(9999)
            logger.debug(received_result.decode())
            #self.logging_func(received_result, host)
            received_result = str(received_result)

【问题讨论】:

    标签: python-3.x logging paramiko


    【解决方案1】:

    这是上述问题的答案

    def debug_file(self, debugfile):
            global logger
            logger = logging.getLogger(debugfile)
            logger.setLevel(logging.DEBUG)
            log_format = logging.Formatter('%(asctime)s %(message)s')
            debug = logging.FileHandler(debugfile, mode='w')
            debug.setFormatter(log_format)
            logger.addHandler(debug)
    
    debugfile = "connection_debug-{0}.log".format(host)
    self.debug_file(debugfile)
        
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多