Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muratbaseren/068dcec80884e9676f61269b0eff6a58 to your computer and use it in GitHub Desktop.
Save muratbaseren/068dcec80884e9676f61269b0eff6a58 to your computer and use it in GitHub Desktop.
Read connectionstrings from appsettings.json to nlog.config
Read connectionstrings from appsettings.json to nlog.config
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<!-- optional, add some variables
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="app-name" value="xxx Common Project"/>
<extensions>
<add assembly="NLog.Appsettings.Standard" />
<!-- write your dll file name that includes custom layout renderer -->
<add assembly="YourDLLFileName" />
</extensions>
<targets>
<target xsi:type="FallbackGroup" name="EMailOrFileOrDb" returnToFirstOnSuccess="true">
<!--Write events and send mail-->
<target name="database" xsi:type="Database" connectionString="${connectionstrings:name=DatabaseContext}" >
<commandText>
insert into dbo.Logs (
AppName, LogDate, Username,Type,Process,Entity,Description,UserId
) values (
@AppName, @LogDate, @Username,@Type,@Process,@Entity,@Description,0
);
</commandText>
<parameter name="@AppName" layout="${app-name}" />
<parameter name="@LogDate" layout="${date}" />
<parameter name="@Username" layout="${username}" />
<parameter name="@Type" layout="Exception Logs" />
<parameter name="@Process" layout="Exception Logs" />
<parameter name="@Entity" layout="${message}" />
<parameter name="@Description" layout="Exception Logs" />
</target>
<target xsi:type="Mail" name="m"
smtpServer="smtp.xxx.com" smtpPort="587"
smtpUserName="noreply@xxx.xom" smtpPassword="xxx"
smtpAuthentication="Basic"
subject="${app-name} ${level} "
layout="${date} ${uppercase:${level}} ${message}${newline}${newline}"
body="
&lt;b&gt;Datetime : &lt;/b&gt;${date}${newline}
&lt;b&gt;Version : &lt;/b&gt;${assembly-version}${newline}
&lt;b&gt;Username : &lt;/b&gt;${username}${newline}${newline}
&lt;b&gt;Controller : &lt;/b&gt;${aspnet-mvc-controller}${newline}
&lt;b&gt;Action : &lt;/b&gt;${aspnet-mvc-action}${newline}
&lt;b&gt;Req. Url : &lt;/b&gt;${aspnet-request-url}${newline}
&lt;b&gt;Req. Querystring : &lt;/b&gt;${aspnet-request-querystring}${newline}${newline}
${message}${newline}${newline}"
header="&lt;b&gt;Logger : &lt;/b&gt;${logger}${newline} &lt;b&gt;Level : &lt;/b&gt;${level}${newline}${newline}"
footer="&lt;b&gt;&lt;small&gt;Bu e-posta xxx tarafından bilgilendirme amacıyla gönderilmiştir.&lt;/small&gt;&lt;/b&gt;"
useSystemNetMailSettings="false"
replaceNewlineWithBrTagInHtml="true"
enableSsl="true" addNewLines="true" html="true"
from="noreply@xxx.com" to="devops@xxx.com" cc="" bcc="" />
<!--Write events to a file with the date in the filename.-->
<target xsi:type="File" name="f"
fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}"
encoding="utf-8" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="EMailOrFileOrDb" />
</rules>
</nlog>
[LayoutRenderer("connectionstrings")]
public class ConnectionStringsLayoutRenderer : LayoutRenderer
{
private static IConfigurationRoot _configurationRoot;
internal IConfigurationRoot DefaultAppSettings
{
get => _configurationRoot;
set => _configurationRoot = value;
}
/// <summary>
/// Global configuration. Used if it has set
/// </summary>
public static IConfiguration AppSettings { private get; set; }
///<summary>
/// The AppSetting name.
///</summary>
[RequiredParameter]
[DefaultParameter]
public string Name { get; set; }
///<summary>
/// The default value to render if the AppSetting value is null.
///</summary>
public string Default { get; set; }
public ConnectionStringsLayoutRenderer()
{
if (AppSettings == null && DefaultAppSettings == null)
{
DefaultAppSettings = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true).Build();
}
}
/// <summary>
/// Renders the specified application setting or default value and appends it to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
if (Name == null) return;
string value = AppSettingValue;
if (value == null && Default != null)
value = Default;
if (string.IsNullOrEmpty(value) == false)
builder.Append(value);
}
private bool _cachedAppSettingValue = false;
private string _appSettingValue = null;
private string AppSettingValue
{
get
{
Name = Name.Replace('.', ':');
if (_cachedAppSettingValue == false)
{
_appSettingValue = AppSettings == null ? DefaultAppSettings.GetConnectionString(Name) : AppSettings[Name];
_cachedAppSettingValue = true;
}
return _appSettingValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment