I try to add some custom fields to NLog using extensibility.
Part of my nlog.config file looks like that : (simplified for exhibit)
<nlog>
<extensions>
<add assembly="Logzio.DotNet.NLog"/>
</extensions>
<variable name="currentUser" value="test" />
<targets async="true">
<target name="logzio" type="Logzio" token="myToken">
<contextproperty name="currentUser" layout="${currentUser}" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logzio" />
</rules>
</nlog>
In every controller, I have something like that (I'm using ASP.NET MVC5)
private static Logger logger = LogManager.GetCurrentClassLogger();
Then I send my logs to logzio using
logger.Fatal("Something bad happens");
Right now, currentUser always have the value test, which is logical.
However, despite of the documentation, I don't understand how to dynamically change currentUser value by the ID of my current logged user.
Should I create a sort of factory ? (if yes, how ? I'm not at ease with factories)
Should I change my logger variable ? If so, how ?
A piece of code would be extremly welcome.
Thank you for pointing my out where I'm wrong
EDIT
After #Rolf's answer, I've created this custom layout renderer
[LayoutRenderer("custom-layout")]
public class CustomLayoutRenderer : LayoutRenderer
{
public string IdUser { get; set; }
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
logEvent.Properties.Add("currentUser", "HowToPassCustomDataHere?");
builder.Append("test from custom-layout");
}
}
and I changed the nlog.config accordingly, adding
layout="${message} ${custom-layout}"
to my <target>
However, I still don't understand how to pass custom value to currentUser. In logz.io, I have "HowToPassCustomDataHere?" as a value of currentUser.
(BTW, ${aspnet-user-identity} is great and works fine ; however I'd like to understand how to pass a custom value to my layout renderer. In my case, something like ${aspnet-user-id})
You can try one of these NLog layoutrenderers to acquire the current username:
${aspnet-user-identity} Wiki
${windows-identity} Wiki
You can also create your own custom NLog LayoutRenderer: https://github.com/NLog/NLog/wiki/How-to-write-a-custom-layout-renderer
Example of how to provide it as currentUser:
<target name="logzio" type="Logzio" token="myToken">
<contextproperty name="currentUser" layout="${aspnet-user-identity}" />
</target>
Related
I'm working on a ASP.NET Core 2.2 MVC application that has NLog set up as its logger. I'm not too familiar with its set up, but we have an nlog.config where we set up our parameter names that we log and the layout renderers for them that get the values. We use using Microsoft.Extensions.Logging; to inject an instance of ILogger into our controller actions and service methods throughout the application.
When we, for example, log something like _logger.LogInformation("Client was created");, along with other pieces of data, we log the name of the authenticated user. This is the ObjectID in the code below, the value of which is taken from HttpContext.User.Identity.Name.
The problem is that I want to log the ObjectID at a point where it's not yet available in HttpContext.User.Identity.Name. This results in a log record without an ObjectID. However, the ObjectID is available in another variable.
Is there a way to log a message and pass the value of a parameter instead of having the logger get it from the layout renderer? I do still want it to use the layout renderer if I'm not passing the parameter manually.
Relevant part of nlog.config:
<commandText>
insert into dbo.Log (
CorrelationId, Application, ObjectID, Logged, Level, Message,
Logger, CallSite, Exception
) values (
#CorrelationId, #Application, #ObjectID, #Logged, #Level, #Message,
#Logger, #Callsite, #Exception
);
</commandText>
<parameter name="#correlationId" layout="${aspnet-traceidentifier}" />
<parameter name="#application" layout="${configsetting:AppSettings.NlogConnection.AppName}" />
<parameter name="#ObjectID" layout="${aspnet-user-identity}" /> <!-- I want to be able to optionally pass the value of this parameter manually -->
<parameter name="#logged" layout="${date}" />
<parameter name="#level" layout="${level}" />
<parameter name="#message" layout="${message}" />
<parameter name="#logger" layout="${logger}" />
<parameter name="#callSite" layout="${callsite:filename=false}" />
<parameter name="#exception" layout="${exception:toString}" />
How we inject and use the logger instance:
public class ClientService : IClientService
{
private readonly ILogger<ClientService> _logger;
public ClientService(ILogger<ClientService> Logger)
{
_logger = Logger;
}
public string CreateClient() {
//some logic to create client
string userName = "John Doe"; // I want to log this as ObjectID in the database
_logger.LogInformation("Client created");
}
}
You can add properties like his:
_logger.LogInformation("Client created {ObjectID}", userName);
And configure #ObjectId-parameter using whenEmpty like this:
<parameter name="#ObjectID" layout="${event-properties:ObjectID:whenEmpty=${aspnet-user-identity}}" />
I have followed many different guides on how to configure the log4net, it is up and running but i can't find a log file anywhere ...
This is how my configuration look like:
Web.Config
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
<log4net debug="true">
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\\temp\\Log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
Global.asax:
XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
//XmlConfigurator.Configure();
StartUp.cs
//[assembly: XmlConfigurator(ConfigFile = "Web.config", Watch = true)]
[assembly: XmlConfigurator(Watch = true)]
Declaration
readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Logging
BasicConfigurator.Configure();
logger.Info("Info logging ...");
logger.Error("Homepage loading test logging ...");
Where my file value is: <file value="C:\\temp\\Log.txt" />
I have tried several paths, and commented out what above but no success.
What am i doing wrong?
UPDATE:
As suggested by John H i have tried configuring and calling the logger in the Application_Start method and tried several alternative configs with it but with no luck. Here are 2 screenshots of some debugging info:
Main properties:
Below are the Logger properties:
What am i doing wrong?
OK so i got it to work following this tutorial: log4net-guide-dotnet-logging
I have created a log4net.config file with content as showed in tutorial.
used [assembly: XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
Called it like this:
ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
logger.Info("Application started.");
file is created and content logged as well.
I am gonna compare the config files content and see if the difference is in there and go gradually comparing everything till i have found what caused it not to work.
Thank you for helping me!
Kind regards
From your screenshots, we can see that your logger is not being initialised with your configuration, because IsDebug is false. One thing I notice from your screenshot, is you're trying to pass the path to Web.config directly to the Configure() method. I realise that may be an attempt to solve the problem, so you may have already tried my next suggestion, but calling Configure() in the manner you currently have won't work because Web.config is not published to your bin\debug folder. It will called Web.projectname.config. Calling
XmlConfigurator.Configure()
with no parameters, will automatically resolve the correct configuration file in your output directory. I'm guessing you've tried that, but if that still doesn't work, try this as well:
using log4net;
protected void Application_Start(object sender, EventArgs e)
{
// Initialising configuration before requesting a logger.
XmlConfigurator.Configure();
// Requesting a logger only after the configuration has been initialised.
var logger = LogManager.GetLogger(typeof(Global));
logger.Info("Application started.");
}
I'm not sure it will make any difference, but your configuration looks fine to me.
But by inspecting the IsDebug property on the logger, you'll at least be able to tell if the configuration has even been read.
Edit: One other thing, make sure the application will have the permissions to write to the file. From the documentation:
The RollingFileAppender extends the FileAppender and has the same behavior when opening the log file. The appender will first try to open the file for writing when ActivateOptions() is called. This will typically be during configuration. If the file cannot be opened for writing the appender will attempt to open the file again each time a message is logged to the appender. If the file cannot be opened for writing when a message is logged then the message will be discarded by this appender.
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;
};
Wondering if anyone has seen this behavior before. My instance of Sitecore 6.6 appends the port number to all the URLs it generates for my site. So for example, a link to the home page should be "https://example.org", but instead it's generated as "https://example.org:443". Everything functions fine with the port numbers, but it's muddling some stuff we're trying to do with SEO and canonicalization. Does anyone know if there's a setting or setup to not produce the port numbers? (I'm sure I could rewrite the URLs by catching them at the appropriate point in the pipeline, but I'm hoping for a simpler way before I jump to that.)
The Sitecore LinkManager is indeed not so clever. We also experienced this issue with a mix of proxy servers and load balancers. To remove the ports, we have created a custom LinkProvider which removes the port if needed (untested code sample):
public class LinkProvider : Sitecore.Links.LinkProvider
{
public override string GetItemUrl(Item item, UrlOptions options)
{
var url = base.GetItemUrl(item, options);
if (url.StartsWith("https://"))
{
url = url.Replace(":443", string.Empty);
}
return url;
}
}
And configure the new LinkProvider:
<configuration xmlns:set="http://www.sitecore.net/xmlconfig/set/">
<sitecore>
<linkManager defaultProvider="sitecore">
<providers>
<add name="sitecore" set:type="Website.LinkProvider, Website" />
</providers>
</linkManager>
</sitecore>
</configuration>
This is caused by having the 'scheme' property in the configuration/sitecore/sites/site element of the web.config (or patched config) being set to 'http' explicitly, but making requests over SSL. Removing this, or setting it to 'https' resolves the issue.
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<sites>
<site patch:before="*[#name='website']"
name="my_website"
hostName="my_website.com"
scheme="http"
...
</sites>
</sitecore>
</configuration>
It's a known bug:
https://kb.sitecore.net/articles/913585
There is a patch for releases below 9.1 available here:
https://github.com/SitecoreSupport/Sitecore.Support.93141/releases
I agree with Jan's findings: setting externalPort on the site node in the configuration convinces Sitecore to exclude the port in a generated URL. I did a full write-up on my blog, including using the result for canonical URL tags.
http://findgnosis.com/2017/06/26/hiding-port-urls-produced-sitecores-linkmanager/
LinkManager:
You can cheat the LinkManager by adding port="443" externalPort="80" to your site-definition in <sites>. Don't know if this will cause other issues though.
<configuration>
<sitecore>
<sites>
<site name="website" port="443" externalPort="80" />
</sites>
</sitecore>
</configuration>
MediaManager:
If you know the url, set the Media.MediaLinkServerUrl-setting, to prevent Sitecore from creating the wrong url. Otherwise...
class SslFriendlyMediaProvider : MediaProvider
{
public override string GetMediaUrl(MediaItem item, MediaUrlOptions options)
{
var url = base.GetMediaUrl(item, options);
if(options.AlwaysIncludeServerUrl)
// https://example.com:443/a b?c=123 --> https://example.com/a%20b?c=123
return new Uri(url).AbsoluteUri;
return url;
}
}
Config:
<configuration xmlns:set="http://www.sitecore.net/xmlconfig/set/">
<sitecore>
<mediaLibrary>
<mediaProvider set:type="SslFriendlyMediaProvider, Assembly" />
</mediaLibrary>
</sitecore>
</configuration>
I'm starting a new project for work, and I decided I want to give MVC a shot. It's a small internal site for a commute challenge.
I want to use Spring.NET for Validation. I have used Spring.NET before in Web Forms, but with no code behind as in traditional ASP.NET, how do I use the Page Validation framework Spring.NET provides?
Edit 1:
In an attempt to try this myself, here is what I have:
Web.Config
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.WebContextHandler, Spring.Web" />
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
<section name="parsers" type="Spring.Context.Support.NamespaceParsersSectionHandler, Spring.Core"/>
</sectionGroup>
</configSections>
<appSettings>
<add key="RouteValidator" value="RouteValidator"/>
<add key="UserValidator" value="UserValidator"/>
</appSettings>
<spring>
<context>
<resource uri="config://spring/objects"/>
<resource uri="~/Config/Spring.Web.cfg.xml" />
<resource uri="~/Config/Spring.Validation.cfg.xml" />
</context>
<parsers>
<parser type="Spring.Validation.Config.ValidationNamespaceParser, Spring.Core" />
</parsers>
</spring>
<system.web>
<httpModules>
<add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web" />
</httpModules>
</system.web>
</configuration>
Spring.Web.Cfg.xml
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd">
<description>
Foo MVC Controller declarations.
</description>
<object id="HomeController" type="Foo.MVC.Web.Controllers.HomeController, Foo.MVC.Web"></object>
<object id="AccountController" type="Foo.MVC.Web.Controllers.RouteController, Foo.MVC.Web"></object>
<object id="RouteController" type="Foo.MVC.Web.Controllers.RouteController, Foo.MVC.Web"></object>
<object id="Spring.Web.UI.Controls.ValidationError" abstract="true">
<property name="Renderer">
<object type="Spring.Web.UI.Validation.IconValidationErrorsRenderer, Spring.Web">
<property name="IconSrc" value="validation-error.gif"/>
</object>
</property>
</object>
<object id="Spring.Web.UI.Controls.ValidationSummary" abstract="true">
<property name="Renderer">
<object type="Spring.Web.UI.Validation.DivValidationErrorsRenderer, Spring.Web">
<property name="CssClass" value="validationError"/>
</object>
</property>
</object>
<object id="standardPage" abstract="true">
<property name="MasterPageFile" value="~/Views/Shared/Site.master"/>
<property name="CssRoot" value="~/Content/"/>
<property name="ImagesRoot" value="~/Content"/>
</object>
</objects>
My validation file is very standard and basically a copy and paste from another project, therefore I didn't include it.
Now the problem I have is how do I use it? How do I get application context? My web forms project users Spring.Web.UI.Page, but I'm worried because the default pages in MVC derive from System.Web.Mvc.ViewPage, so that isn't going to work.
Or am I just not able to use Spring.NET's framework for MVC quite yet?
Thanks!
Thanks for any assistance.
You definitely can use Spring with ASP.Net MVC. You need to register that you are using it in the Global.ascx class then the framework will create Controllers based on what you have defined in your config file.
public class MvcApplication : System.Web.HttpApplication
{
...Routes stuff...
protected void Application_Start()
{
ControllerBuilder.Current.SetControllerFactory(typeof(ControllerFactory));
RegisterRoutes(RouteTable.Routes);
}
}
public class ControllerFactory : IControllerFactory
{
public IController CreateController(RequestContext requestContext, string controllerName)
{
return IoC.Resolve<IController>(controllerName);
}
public void ReleaseController(IController controller)
{
//This is a sample implementation
//If pooling is used write code to return the object to pool
if (controller is IDisposable)
{
(controller as IDisposable).Dispose();
}
controller = null;
}
}
public static class IoC
{
static readonly IObjectFactory Factory
= new XmlObjectFactory(new FileSystemResource
(HttpContext.Current.Server.MapPath("~/Config/Spring.config")));
public static T Resolve<T>(string name)
{
return (T)Factory.GetObject(name);
}
}
Just make sure that the path to your spring config file is correct! This was adapted from this link.
On a wider note, this approach does not allow you to Spring the page classes, and being an MVC architecture, where views are pretty dumb classes, does not really support rich validation in the view itself in the manner you suggest. Look at either including the validation in the Model (post-back) in JQuery.
In best of my knowledge, the Spring Validation is not supported up to the latest release of ASP.NET MVC (1.0) and Spring.NET framework (1.3).
As far as incorporating Spring.NET with MVC, you can use MvcContrib project and come to the same code-base as posted by Colin Desmond (but you don't have to do the dirty work yourself).