com+组件日志记录(log4net)
网上找了一个操作powershell的com+组件源码,配置好后,发现启用邮箱不稳定。因此在代码中用log4net加入异常日志记录。如下:
private static readonly ILog log = LogManager.GetLogger("ErrorLog"); public bool IsExistMailBox(string identity) { try { PSSnapInException PSException = null; RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create(); runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out PSException); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); string errors = string.Empty; using (pipeline) { Command command = new Command("Get-Mailbox"); command.Parameters.Add("identity", identity); //command.Parameters.Add("DomainController", "XX"); pipeline.Commands.Add(command); Collection<PSObject> result = pipeline.Invoke(); if ((pipeline.Error != null) && (pipeline.Error.Count > 0)) { foreach (object obj2 in pipeline.Error.ReadToEnd()) { errors = errors + obj2.ToString() + "|"; } //记录log信息 log.Info(identity + "PipeLine[Get-Mailbox]错误信息:" + errors); throw new Exception(errors);//记录log信息 } } pipeline = null; runspace.Close(); runspace = null; //return (result != null && result.Count > 0); return string.IsNullOrEmpty(errors); } catch (System.Exception ex) { log.Info(identity + "账户Get-Mailbox调用异常:" + ex.Message); throw ex; } }
log4Net配置节:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> </configSections> <log4net> <appender name="ErrorLog" type="log4net.Appender.RollingFileAppender,log4net" > <param name="File" value="D:\\Logs\\Error\\" /> <param name="AppendToFile" value="true" /> <param name="RollingStyle" value="Date" /> <param name="DatePattern" value="yyyy-MM\\"ServiceError-"yyyy-MM-dd".txt"" /> <param name="StaticLogFileName" value="false" /> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%d{yyy-MM-dd HH:mm:ss} %m%n" /> </layout> </appender> <root> <level value="ALL" /> </root> <!-- 服务错误日志--> <logger name="ErrorLog"> <level value="INFO" /> <appender-ref ref="ErrorLog" /> </logger> </log4net> </configuration>
AssemblyInfo.cs顶部加入如下代码:
[assembly: log4net.Config.Repository("PowerShellExInfo")] [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
以上都做好后,创建com组件。将log4Net配置文件放到引用组件同目录下。本来以为这样就可以了,可是操作过程中发现并没有记录异常日志信息,网上找了三天,皇天不负有心人啊,终于在国外论坛找到解决方法。log4net配置文件应放到在system32目录下,这样日志就能记录了。OK