从powershell-script登录到csharp-program(log4net-logfile)

我用C#编写了一个程序,它创建了一个日志文件并使用log4net填充它。 该程序启动PowerShell脚本。 脚本也应该使用log4net。 我想监视脚本在运行时记录到log4net的内容,并在我的日志文件中写入此信息。

您知道我是如何做到这一点的,或者我在哪里获得有关我的问题的信息/帮助?

谢谢

您可以定义一些函数并将它们作为变量传递给您的脚本:

static void Log(string message) { // log4net code here... } void ExecuteScript() { // create the runspace configuration RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); // create the runspace, open it and add variables for the script Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); // pass the Log function as a variable runspace.SessionStateProxy.SetVariable("Log", (Action)Log); // etc... 

然后你可以像这样调用脚本中的函数:

 $Log.Invoke("test") 

编辑 :要添加日志记录级别,您应该执行类似的操作

  static void Log(LogLevel level,string message) { // log4net code here... } void ExecuteScript() { // ... runspace.SessionStateProxy.SetVariable("Log", (Action)Log); 

作为替代方案,您可以重新路由流并在脚本中使用标准的Write-Error,Write-Verbose等CMDlet。

在您的C#app中附加流事件的方法,如下所示:

 PowerShell ps = PowerShell.Create(); // ... code to add your script, etc. ps.Streams.Warning.DataAdded += new EventHandler(Warning_DataAdded); // ... attach more streams for other log levels ps.Invoke(); 

像这样创建你的方法:

 static void Warning_DataAdded(object sender, DataAddedEventArgs e) { PSDataCollection warningStream = (PSDataCollection)sender; log.Warn(warningStream[e.Index].Message); } 

这应该通过您的PowerShell脚本编写您输出的所有内容

 Write-Warning "This is a warning message" 

到log4net中的警告级别。

我没有特定于log4net的详细信息,但应该可以像任何其他.Net组件一样加载log4net:

从Powershell Powershell 访问.NET组件 调用使用App.config的.NET程序集