Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

c# - NLog Replace Layout Renderer not work with json content

I use a third party package that depending on Nlog 4.7 and NLog.AspNetCore 4.8, and the package will write log.

In my Nlog.config

<logger name="package namespace" level="Info" writeTo="packageFile" />
<target xsi:type="File" name="packageFile" fileName="${baseFilePath}/packageFile.log" KeepFileOpen="true" layout="${message}" concurrentWrites="true" />

It's work, but now I need replace content in message. I find Replace Layout Renderer that is I need.

The message is json string like this:

{"ABC":{"DEF":"AA00014325","GHI":"01"}} 

I want to replace message become

{"ABC":{"DEF":"A****14325","GHI":"01"}} 

This is the pattern I have used: [A-Z]d{1}d{2} I used this to test it against: https://regex101.com/

Update: I also try the pattern by .NET Regex Tester

My Nlog.config like this:

<variable name ="messageReplace" value="${replace:inner=${message}:searchFor=[A-Z]\d{1}\d{2}:replaceWith=****:regex=true}" />
<logger name="package namespace" level="Info" writeTo="packageFile" />
<target xsi:type="File" name="packageFile" fileName="${baseFilePath}/packageFile.log" KeepFileOpen="true" layout="${messageReplace}" concurrentWrites="true" />  

But it's not work......

I change my Nlog.config like this:

<variable name ="message1" value="AA00014325" />
<variable name ="messageReplace" value="${replace:inner=${message1}:searchFor=[A-Z]\d{1}\d{2}:replaceWith=****:regex=true}" />
<logger name="package namespace" level="Info" writeTo="packageFile" />
<target xsi:type="File" name="packageFile" fileName="${baseFilePath}/packageFile.log" KeepFileOpen="true" layout="${messageReplace}" concurrentWrites="true" /> 

It's working...but if change message1 to

"AA00014325"

It not working again....Why?

I want to replace json string in message, how can I do?

Information:

  • Platform : ASP.NET Core 3
  • Nlog version : 4.7
  • NLog.AspNetCore version : 4.8

Thank you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So using this configuration, I got it to work as per screenshot. Somethings to bear in mind is that the configuration is XML so to escape correctly. But I see you got that right ?. So I believe its down to your regex.

 <variable name="messageNoDigits" value="${replace:inner=${message}:searchFor=[A-Z]\d{3}:replaceWith=****:regex=true}" />

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...