Last active
December 7, 2019 20:42
-
-
Save muratbaseren/068dcec80884e9676f61269b0eff6a58 to your computer and use it in GitHub Desktop.
Read connectionstrings from appsettings.json to nlog.config
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Read connectionstrings from appsettings.json to nlog.config |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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=" | |
<b>Datetime : </b>${date}${newline} | |
<b>Version : </b>${assembly-version}${newline} | |
<b>Username : </b>${username}${newline}${newline} | |
<b>Controller : </b>${aspnet-mvc-controller}${newline} | |
<b>Action : </b>${aspnet-mvc-action}${newline} | |
<b>Req. Url : </b>${aspnet-request-url}${newline} | |
<b>Req. Querystring : </b>${aspnet-request-querystring}${newline}${newline} | |
${message}${newline}${newline}" | |
header="<b>Logger : </b>${logger}${newline} <b>Level : </b>${level}${newline}${newline}" | |
footer="<b><small>Bu e-posta xxx tarafından bilgilendirme amacıyla gönderilmiştir.</small></b>" | |
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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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