c# - 从 powershell 脚本记录到 csharp 程序(log4net - 日志文件)

标签 c# .net powershell log4net

我用 C# 编写了一个程序,它创建了一个日志文件并使用 log4net 填充它。该程序启动 powershell-scripts。脚本也应该使用 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<string>)Log);
        // etc...

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

$Log.Invoke("test")

编辑:要添加日志记录级别,您应该做类似的事情

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

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

关于c# - 从 powershell 脚本记录到 csharp 程序(log4net - 日志文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3977247/

相关文章:

.net - IO.FileNotFoundException 但文件应该存在

powershell - 使用 PowerShell 查找所有已安装的应用程序?

powershell - 使用Powershell将电子邮件地址添加到AD安全组

资源的 C# Uri 生成器

c# - WCF 服务关闭

c# - 如何在 C# 中读取 RegEx 捕获

c# - 如何加载位于 .NET Core 控制台应用程序文件夹中的程序集

arrays - Powershell从CSV文件中的所有列构建所有可能组合的数组

c# - 如何修改所选选项卡中的控件 - C#

c# - 将数组的 2 个部分合并为 1