从PowerShell的脚本日志记录到CSHARP程序

从PowerShell的脚本日志记录到CSHARP程序

本文介绍了从PowerShell的脚本日志记录到CSHARP程序(log4net的 - 日志文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写C#程序,创建一个日志文件,并使用log4net的填补了这个。该程序将启动PowerShell的脚本。这些脚本应该使用log4net的,太。我要监视的脚本日志,而他们正在运行到log4net的,写在我的日志文件的信息。

I have written a program with C#, that creates a logfile and fills this by using log4net. This program starts powershell-scripts. The scripts should use log4net, too. I want to monitor what the scripts log to log4net while they are running and write this information in my logfile.

你有一个想法,我是如何做到这一点还是从哪里获得信息/帮助我的问题?

Have you an idea how I do this or where I get information/help to my problem?

感谢

推荐答案

您可以定义一些功能,并传递给你的脚本变量:

You could define some functions and pass them to your script as variables:

    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<string>)Log);
        // etc...

然后就可以从这样的脚本中调用该函数:

Then you can invoke the function from the script like this:

$Log.Invoke("test")

修改:添加日志记录级别,你应该做这样的事情

EDIT: to add a logging level, you should do something like

    static void Log(LogLevel level,string message) {
        // log4net code here...
    }

     void ExecuteScript() {
        // ...
        runspace.SessionStateProxy.SetVariable("Log", (Action<LogLevel,string>)Log);

这篇关于从PowerShell的脚本日志记录到CSHARP程序(log4net的 - 日志文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 17:27