Python日志代码导致类运行终止,请求排查原因
排查Netweb类无法运行的问题
以下代码导致我的Netweb类无法运行,我推测问题出在logger.FileHandler模块,但相同代码在其他脚本里能正常执行。已经确认文件路径存在,且IIS服务器用户有写入权限。日志通过logger.info(f'get_vlans({ip_address}, {int_len}, {type})')调用,所有传入变量值都验证正确。
日志代码
import logging import datetime now = datetime.datetime.now() now = now.strftime("%m-%Y") # create logger with the name 'gp_uccx_app' logger = logging.getLogger('netweb_logger') logger.setLevel(logging.DEBUG) # # create file handler fh = logging.FileHandler(f'C:/inetpub/wwwroot/site1/python/custom/logs/log-{now}.txt') fh.setLevel(logging.DEBUG) # create formatter and add it to the handler formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) fh.setFormatter(formatter) # add the handler to the logger logger.addHandler(fh)
Netweb类代码
class Netweb: # Collects the vlans for all interfaces in the stack that have the line 'switchport access vlan' in the running config def get_vlans(ip_address, int_len, type): logger.info(f'get_vlans({ip_address}, {int_len}, {type})') vlans = [] try: reSearch = '' if int_len == 'long' and type == 'gigabitethernet': reSearch = "^interface GigabitEthernet\d\/0\/\d" elif int_len == 'long' and type == 'fastethernet': reSearch = "^interface FastEthernet\d\/\d" elif int_len == 'short' and type == 'gigabitethernet': reSearch = "^interface GigabitEthernet\d\/\d" elif int_len == 'short' and type == 'fastethernet': reSearch = "^interface FastEthernet\d\/\d" net_connect = ConnectHandler( device_type=platform, ip=ip_address, username=cisco_username, password=cisco_password ) output = net_connect.send_command( 'show run | i (interface)|.(access vlan)' ) net_connect.disconnect() output = output.splitlines() x = 0 for out in output: if re.search( reSearch, out ): interface = out.split() interface = interface[ 1 ] if 'access vlan' in output[ x + 1 ]: vlan = output[ x + 1 ].split( 'switchport access vlan' )[1].strip() else: vlan = '1' vlans.append( [ interface, vlan ] ) x = x + 1 return vlans except Exception as e: logger.info(e)
排查方向
- 类方法定义错误:
get_vlans是Netweb类中的方法,但未添加self参数,也没有@staticmethod装饰器。如果是实例方法,第一个参数必须是self;如果不需要实例化调用,要加上@staticmethod,否则调用时会抛出参数不匹配的异常。这很可能是类无法运行的核心原因。 - 日志处理器重复添加:若日志模块被多次导入,会重复给
netweb_logger添加FileHandler,引发文件占用或写入失败。可以在添加处理器前做判断:if not logger.hasHandlers(): fh = logging.FileHandler(f'C:/inetpub/wwwroot/site1/python/custom/logs/log-{now}.txt') # 后续设置格式、添加处理器的代码 - 未导入依赖模块/变量:Netweb类中用到的
re、ConnectHandler、platform、cisco_username、cisco_password均未在代码中体现导入或定义,这些未定义项会直接抛出异常。如果日志初始化失败,异常信息无法被记录,会误导你认为是日志模块的问题。 - IIS权限验证:虽然确认了写入权限,但需验证IIS应用池身份是否真的拥有该路径的创建、修改文件权限。可以用该身份手动执行一个简单的文件写入脚本,比如:
看是否能成功写入。with open('C:/inetpub/wwwroot/site1/python/custom/logs/test.txt', 'w') as f: f.write('test') - 异常日志降级排查:如果怀疑日志模块有问题,可在
get_vlans的异常块中添加基础文件写入,绕过日志模块直接记录异常:
以此确认到底是日志模块的问题,还是其他代码逻辑的问题。except Exception as e: with open('C:/inetpub/wwwroot/site1/python/custom/logs/error.txt', 'a') as f: f.write(f'{datetime.datetime.now()}: {str(e)}\n')
内容的提问来源于stack exchange,提问作者Blinkydamo
相关产品推荐
相关产品推荐

