How to set formatProvider property in Serilog from app.config file - serilog

I know that it's possible to setup Serilog sinks in app.config file (AppSettings section) and it's pretty simple with scalar types, but how to be with complex ones (IFormatProvider etc.). Does anybody know how to deal with that and is it possible at all?
I'm trying to simulate this example
ILogger logger = new LoggerConfiguration()
.Enrich.WithExceptionDetails()
.WriteTo.Sink(new RollingFileSink(
#"C:\logs",
new JsonFormatter(renderMessage: true))
.CreateLogger();
but using app.config only.

You can use something like JsonRollingFile for this.
<configuration>
<appSettings>
<add key="serilog:using:Json" value="Serilog.Sinks.Json" />
<add key="serilog:write-to:JsonRollingFile.pathFormat" value="C:\Logs\myapp-{Date}.jsnl" />
</appSettings>
</configuration>

Related

Get Mail Setting from Web.Config in SendAsync Method?

I am working on Forgot Password Functionality. In my web.config file I have done the mail settings:
<system.net>
<mailSettings>
<smtp from="email">
<network host="host" port="25" userName="" password="=" enableSsl="true" />
</smtp>
</mailSettings>
</system.net>
In my SendAsync method I am trying to read setting from web.config:
SmtpClient client = new SmtpClient();
return client.SendMailAsync(ConfigurationManager.AppSettings["SupportEmailAddr"],
message.Destination,
message.Subject,
message.Body);
I have no idea what is this: AppSettings["SupportEmailAddr"]
I took this from here.
It is giving me following exception:
Value cannot be null. Parameter name: from
In your web.config file you have a section called: <appSettings>.
That is what ConfigurationManager.AppSettings is referring too.
["SupportEmailAddr"] is looking at a specific setting called SupportEmailAddr.
In your web.config it would look something like this:
<appSettings>
<add key="SupportEmailAddr" value="someone#example.com" />
</appSettings>
You are getting the value cannot be null message because you will not have the setting in your web.config as above.
So to fix the error message find your <appSettings> and add:
<add key="SupportEmailAddr" value="someone#example.com" />
Alternatively, if you have the current value in your AppSettings already then just change the key that you are looking for in the C# code.
ConfigurationManager.AppSettings["CorrectAppSettingKey"]
Note: if you plan on using any of the web.config inheritance features you should WebConfiguratonManger.AppSettings instead of ConfigurationManager.AppSettings. See the difference between the two here: What's the difference between the WebConfigurationManager and the ConfigurationManager?

How to override Elmah applicationname set in Web.config

We have a multi-tenanted MVC app, meaning that exactly the same app is published to multiple IIS virtual directories / applications, and then the app its self works out who it is, and skins its self (css) accordingly.
This is all very well, but anything logged by ELMAH in our elmah database gets logged under the same applicationName, as this is pulled out of Web.Config elmah section below where everything would be logged as "MyappName" :
<configuration>
[...]
<elmah>
<security allowRemoteAccess="false" />
<errorLog
type="Elmah.SqlErrorLog, Elmah"
connectionStringName="elmah"
applicationName="MyappName" />
</elmah>
</configuration>
The question is therefore how to override the applicationName setting from web.config with something specific so we can distinguish errors for a given tenant web site.
As this is configurable within the web.config, ELMAH are already providing you with a way to specify the application name when the application is deployed to different locations - it's just a case of making use of it.
This would generally be something that you would manipulate as part of your deployment steps. If you are doing it manually then it's going to be a pain, but it could be easily manipulated by using a web.config transform.
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<elmah>
<errorLog applicationName="MyappName" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
</elmah>
</configuration>
I wonder if the following might work, if you put the following into your Global.asax:
var service = ServiceCenter.Current;
ServiceCenter.Current = context =>
{
var connectionString = "YOUR CONNECTION STRING";
var container = new ServiceContainer(service(context));
var log = new SqlErrorLog(connectionString) { ApplicationName = "APP NAME HERE" };
container.AddService(typeof(ErrorLog), log);
return container;
};

App.config and web.config?

How do i read from app.config and web.config.
app.config reading is as follows .how do i read from web.config
using System.Configuration;
string configvalue1 = ConfigurationManager.AppSettings["countoffiles"];
string configvalue2 = ConfigurationManager.AppSettings["logfilelocation"];
also why do we store in these config files?
And How do i read from a user defined tag <display> in app.config below ??
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<display>
<add key="countoffiles" value="7" />
<add key="logfilelocation" value="abc.txt" />
</display>
</configuration>
what is the difference between values stored in app.config and web.config?
How do i decide where to keep certain data?
i got this error when i added <display> tag to the web.config in MVC application.Any clues on why??
Web.Config is used for applications hosted at IIS (Websites, Webservices)
App.Config is used for any other .NET applications like (WinForms, WPF, Windows Services)
To read from custom section I would go that way:
NameValueCollection displaySection = (NameValueCollection)ConfigurationManager.GetSection("display");
string countoffiles = displaySection ["countoffiles"];
string logfilelocation = displaySection ["logfilelocation"];
In regards to configuring custom sections, please check that article:
https://msdn.microsoft.com/en-us/library/2tw134k3.aspx

Is there a way to configure multiple Serilog RollingFiles through appSetting configuration

Is there a way to configure multiple Serilog RollingFiles through appSetting?
I want to create separate log files for Information and Error levels.
Configuring multiple logs is pretty simple in appsettings, mission is to use filter. i spent almost 3hours trying to figure out how to archieve this.
I ended up doing the following:
Startup.cs / Global.asax.cs
Log.Logger = new LoggerConfiguration()
.WriteTo
.Logger(x => x.Filter
.ByIncludingOnly(logEvent => logEvent.Level == Serilog.Events.LogEventLevel.Error)
.ReadFrom
.AppSettings("error"))
.WriteTo
.Logger(x => x.Filter
.ByIncludingOnly(logEvent => logEvent.Level == Serilog.Events.LogEventLevel.Information)
.ReadFrom
.AppSettings("info")).CreateLogger()
Web.Config
<add key ="error:serilog:using:RollingFile" value="Serilog.Sinks.RollingFile"/>
<add key ="error:serilog:write-to:RollingFile.pathFormat" value="C:\log\error {Date}.txt"/>
<add key ="error:serilog:write-to:RollingFile.formatter" value="Serilog.Formatting.Json.JsonFormatter"/>
<add key ="info:serilog:using:RollingFile" value="Serilog.Sinks.RollingFile"/>
<add key ="info:serilog:write-to:RollingFile.pathFormat" value="C:\log\info {Date}.txt"/>
<add key ="info:serilog:write-to:RollingFile.formatter" value="Serilog.Formatting.Json.JsonFormatter"/>
Not directly - it's possible to use a setting prefix like:
.ReadFrom.AppSettings()
.ReadFrom.AppSettings(settingPrefix: "2")
And then add the additional sink like:
<add key="2:serilog:write-to:RollingFile.pathFormat" value="..." />
Baking this properly into the app settings configuration provider has been a "TODO" for a while.
If configuring the sinks in code is possible, that's probably the way to go.

asp.net mvc: disabled RoleManager is still executed

I have a web site where configured with:
<roleManager enabled='false'></roleManager>
But I still can see roleManager being executed in the pipeline (by looking at traces, also I am getting exception when roleManager tries to load roles from SQL providers configured in machine.config)
How can I disable roleManager?
fix
add enableSimpleMembership with value false app setting to your web.config.
cause
<roleManager enabled="false" />
will cause Roles.Enabled flag to be set to false, as expected,
but there is WebMatrix.WebData.WebSecurity that says:
internal static void PreAppStartInit()
{
if (!ConfigUtil.SimpleMembershipEnabled)
return;
...
Roles.Enabled = true;
...
}
this will override roleManager setting (this code is executed before RoleManager module is).
to disable SimpleMembership you can add app setting enableSimpleMembership with value="false" (web.config):
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<appSettings>
<add key="enableSimpleMembership" value="false" />
</appSettings>
</configuration>
this will prevent webmatrix from enabling RoleManager.
Another solution (hack) is to remove RoleManager module from the list of modules:
....
<system.webServer>
<modules>
<remove name="RoleManager"/>
</modules>
....
no... I don't think it's correct, even with enableSimpleMembership=false, you'd still need to implement a Dummy RoleProvider, otherwise, exception "The Role Manager feature has not been enabled."
Here's how to implement a dummy RoleProvider:
Turning off only the Role Provider in SimpleMembership

Resources