How do I log the Console output of a hosted scriptcs execution?

498 Views Asked by At

I am using scriptcs.net to host dynamic scripts, and I would like to capture the output from Console.WriteLine() into my log as information, and Console.Error.WriteLine() as errors. Same as the way Octopus Deploy custom script logging.

The reason I would like to capture the Console.WriteLine() output is to make it easy for script writers to log information using a familiar tool.

Here is my script hosting function:

    public static dynamic RunScript()
    {
        var logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        var scriptServicesBuilder = new ScriptServicesBuilder(new ScriptConsole(), logger).
            LogLevel(LogLevel.Info).Cache(false).Repl(false).ScriptEngine<RoslynScriptEngine>();

        var scriptcs = scriptServicesBuilder.Build();

        scriptcs.Executor.Initialize(new[] { "System.Web" }, Enumerable.Empty<IScriptPack>());
        scriptcs.Executor.AddReferences(Assembly.GetExecutingAssembly());

        var result = scriptcs.Executor.Execute("Hello.csx");

        scriptcs.Executor.Terminate();

        if (result.CompileExceptionInfo != null)
            return new { error = result.CompileExceptionInfo.SourceException.Message };
        if (result.ExecuteExceptionInfo != null)
            return new { error = result.ExecuteExceptionInfo.SourceException.Message };

        return result.ReturnValue;
    }

The contents of my Hello.csx file:

Console.WriteLine("This output is lost forever");

So my question is how can I capture the text written to Console.WriteLine() and save it?

0

There are 0 best solutions below