NLog - how can I encrypt the logged stacktrace in the database

I would suggest writing a LayoutRendererWrapper. A LayoutRendererWrapper allows you to "wrap" a LayoutRenderer so that you can apply processing to the output. In the case of encrypting the stack trace, you can configure NLog to add the StackTrace to the output, but you can wrap the StackTrace layout renderer so that you can apply your encryption.

You see examples of LayuoutRendererWrappers in NLog's source code repository.

Actually, the general nature of the LayoutRendererWrapper means that you can write an encrypting wrapper and apply it to any LayoutRenderer. So, you could, for example, encrypt the stack trace and the message, but leave the rest of the fields as clear text.

Here is an example (untested) of how you might write an encrypting LayoutRendererWrapper:

namespace NLog.LayoutRenderers.Wrappers
{
  using System.ComponentModel;
  using System.Globalization;
  using NLog.Config;

  [LayoutRenderer("Encrypt")]
  [AmbientProperty("Encrypt")]
  [ThreadAgnostic]
  public sealed class EncryptLayoutRendererWrapper : WrapperLayoutRendererBase    
  {
    public EncryptLayoutRendererWrapper()
    {
      this.Culture = CultureInfo.InvariantCulture;
      this.Encrypt = true;
    }

    [DefaultValue(true)]
    public bool Encrypt { get; set; }

    public CultureInfo Culture { get; set; }

    protected override string Transform(string text)
    {
      return this.Encrypt ? Encrypt(text) : text;
    }

    protected string Encrypt(string text)
    {
      //Encrypt your text here.
    }
  }
}

I think it would be configured like this in the NLog.config file:

${longdate} | ${logger} | ${level} | ${encrypt:${stacktrace}} | ${message}

I'm not sure how you would configure it programmatically as I don't normally use programmatic configuration.