Logging from powershell-script to csharp-program (log4net - logfile)

后端 未结 3 1732
萌比男神i
萌比男神i 2021-01-06 09:53

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

相关标签:
3条回答
  • 2021-01-06 10:17

    I do not have details specific to log4net but it should be possible to load log4net like any other .Net component:

    Accessing .NET components from Powershell Powershell Calling .NET Assembly that uses App.config

    0 讨论(0)
  • 2021-01-06 10:21

    As an alternative you could reroute the streams and use the standard Write-Error, Write-Verbose, etc. CMDlets in your Script.

    In your C# app attach methods to the streams events, like so:

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

    Create your methods like so:

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

    This should write everything you output in your PowerShell Script via

    Write-Warning "This is a warning message"
    

    to the Warn level in log4net.

    0 讨论(0)
  • 2021-01-06 10:30

    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);
    
    0 讨论(0)
提交回复
热议问题