question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

A sink for PowerShell `Write-Debug`, `Write-Verbose`, etc.?

See original GitHub issue

A few questions before you begin:

Does this issue relate to a new feature or an existing bug?

  • Bug
  • [x ] New Feature

What version of Serilog is affected? Please list the related NuGet package.

All

**What is the target framework and operating system? See [target frameworks]

  • [x ] netCore 3.1
  • netCore 2.0
  • netCore 1.0
  • 4.7
  • 4.6.x
  • 4.5.x

Please describe the current behavior?

I can’t find a Serilog sink that I can use from a PowerShell CmdLet that I’m building in C#. The CmdLet utilizes a library I’ve built that makes extensive use of Serilog for Debug and Information.

I currently setup Serilog like this:

            // Setup logging
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.ControlledBy(MasterLevelSwitch)
                .WriteTo.Console(levelSwitch: ConsoleLevelSwitch)
                .WriteTo.Debug(levelSwitch: DebugLevelSwitch)
                .WriteTo.File(LogPath, shared: true, levelSwitch: FileLevelSwitch)
                .CreateLogger();

I want to be able to add to my configuration, when my library is used from PowerShell:

            // Setup logging
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.ControlledBy(MasterLevelSwitch)
                .WriteTo.PowerShellWriteVerbose(levelSwitch: ConsoleLevelSwitch)
                .WriteTo.PowerShellWriteDebug(levelSwitch: DebugLevelSwitch)
                .WriteTo.File(LogPath, shared: true, levelSwitch: FileLevelSwitch)
                .CreateLogger();

(roughly).

I’ve searched for a Serilog sink for PowerShell’s Write-Output, Write-Verbose, Write-Debug, etc… to no avail. I suppose it wouldn’t be hard to write one, but I can’t believe I’m the first person to think of this…

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
sandscap-sccommented, Jun 18, 2020

@tig Would it be safer to instantiate the StringWriter strWriter = new StringWriter(); inside the _syncRoot lock? Otherwise, other threads might change the strWriter variable before the writer gets a chance to write out the message.

public void Emit(LogEvent logEvent) {
            if (logEvent == null) throw new ArgumentNullException(nameof(logEvent));

            lock (_syncRoot) {

                StringWriter strWriter = new StringWriter();
                TextFormatter.Format(logEvent, strWriter);

                switch (logEvent.Level) {
                    // -Verbose
                    case LogEventLevel.Verbose:
                    case LogEventLevel.Information:
                        _cmdlet.WriteVerbose(strWriter.ToString());
                        break;
...
0reactions
rstuttoncommented, Jan 15, 2021

@tig thanks for your PowershellSink example. I found that the (text) output capability of Cmdlet was limiting - especially when you want to simply write to stderr - but AsyncCmdlet derives from a PSCmdlet which has a Host property, which in turn has a UI property of type PSHostUserInterface and this is much more useful:

namespace System.Management.Automation.Host
{
    public abstract class PSHostUserInterface
    {
        protected PSHostUserInterface();

        public abstract PSHostRawUserInterface RawUI { get; }
        public virtual bool SupportsVirtualTerminal { get; }

        public abstract Dictionary<string, PSObject> Prompt(string caption, string message, Collection<FieldDescription> descriptions);
        public abstract int PromptForChoice(string caption, string message, Collection<ChoiceDescription> choices, int defaultChoice);
        public abstract PSCredential PromptForCredential(string caption, string message, string userName, string targetName);
        public abstract PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options);
        public abstract string ReadLine();
        public abstract SecureString ReadLineAsSecureString();
        public abstract void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value);
        public abstract void Write(string value);
        public abstract void WriteDebugLine(string message);
        public abstract void WriteErrorLine(string value);
        public virtual void WriteInformation(InformationRecord record);
        public virtual void WriteLine();
        public virtual void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value);
        public abstract void WriteLine(string value);
        public abstract void WriteProgress(long sourceId, ProgressRecord record);
        public abstract void WriteVerboseLine(string message);
        public abstract void WriteWarningLine(string message);
    }
}

Read more comments on GitHub >

github_iconTop Results From Across the Web

Write-Debug (Microsoft.PowerShell.Utility)
The Test-Debug function writes the value of the $DebugPreference variable to the PowerShell host and to the Debug stream. In this example, we...
Read more >
OutNullCommand Class (Microsoft.PowerShell.Commands)
Null sink to absorb pipeline output. ... Gets an object that surfaces the current PowerShell transaction. ... WriteDebug(String). Display debug information.
Read more >
OutDefaultCommand Class (Microsoft.PowerShell. ...
Implementation for the out-default command this command it implicitly inject by the powershell host at the end of the pipeline as the default...
Read more >
Let's Kill Write-Output (Get-PowerShellBlog /u/markekraus)
I'll often turn a Write-Verbose into a Write-Debug if it is inside nested foreach loops or in functions that get called with high...
Read more >
Building PowerShell Functions – Best Practices
Don't build in everything but the kitchen sink. ... Use write-verbose, write-debug and write-error to provide insight at the shell ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found