I'm developing an ASP.net core (2.2) MVC application but I can't get the logging to work. The AspNetCore layout renderers return empty values. I installed following packages:
<PackageReference Include="NLog" Version="4.6.2" />
<PackageReference Include="NLog.Extensions.Logging" Version="1.4.0" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.8.1" />
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"
autoReload="true"
internalLogLevel="Trace"
internalLogFile="c:\temp\internal-nlog.txt">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
<!-- another file log, only own logs. Uses some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-api-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxlevel="Info" final="true" />
<logger name="IdentityServer4.*" maxlevel="Info" final="true" />
<!-- BlackHole without writeTo -->
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
Startup.cs
services.AddLogging(builder =>
{
builder.ClearProviders();
builder.SetMinimumLevel(LogLevel.Trace);
builder.AddNLog();
});
Log:
2019-04-19 11:55:01.2521||INFO|MyApp.API.Controllers.ConfigController| |url: |action:
The easy way is just to follow the wiki-guide, and call UseNLog():
https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2#4-update-programcs
But if you like to do things your own way, and do it like in ASP.NET Core ver. 1:
https://github.com/NLog/NLog/issues/2859#issuecomment-415865357
Related
I've recently started writing .Net Core applications and I'm using NLog for my logging. I came up with the following NLog.config file. This will log if I use _log.LogInformation("Log an INFO"); but not if I use _log.LogDebug("Log a DEBUG");.
I do not have any logging settings in my appsettings.json file. I typically write console applications and VisualStudio template for console apps does not have any logging automatically added to appsettings.
I'm using .Net Core 3.1 with the following NLog package.
<PackageReference Include="NLog.Web.AspNetCore" Version="4.9.3" />
Anyone see why using the Debug wouldn't write to the log file?
<?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"
autoReload="true">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<variable name="LogDirectory" value="D:\logs\ProjectName"/>
<!-- the targets to write to -->
<targets>
<target xsi:type="File"
name="DefaultTarget"
fileName="${LogDirectory}\LogFile.log"
layout="${longdate} | ${callsite} | ${message}"
archiveAboveSize="3145728"
archiveEvery="Day"
archiveFileName = "${LogDirectory}/Archive/{#}.log"
archiveNumbering = "DateAndSequence"
archiveDateFormat = "yyyyMMdd"
maxArchiveFiles = "21"
/>
<target name="ConsoleTarget"
xsi:type="Console"
layout="${longdate} ${logger:shortName=True} ${message} ${onexception:EXCEPTION OCCURRED\:${exception:format=type,message,StackTrace,method:maxInnerExceptionLevel=8:innerFormat=type,message,StackTrace,method}}"
/>
</targets>
<rules>
<logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- BlackHole without writeTo -->
<logger name="*" minlevel="Debug" writeTo="DefaultTarget,ConsoleTarget" />
</rules>
</nlog>
I am using log4net currently and on every hour log file archive is being performed.
Now I am changing log4net to NLog
Is there similar setting available in NLog Like rolingStyle="once"? which was configure setting available in log4net.
For example earlier while using log4net the files created were used to be like:
LogFile.log
LogFile.log.1 <-last archive file
Following is configuration I used in log4net and I want to use the exact configure settings so that archived file naming should remains as it was in log4net:
<appender name="Work" type="RMM.Common.Logger.LogFileRollingAppender, Common">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<dateTimeStrategy type="log4net.Appender.RollingFileAppender+UniversalDateTime" />
<file type="log4net.Util.PatternString" value="%property{EdgeAPILogPath}\WebAPI_Work.log" />
<param name="AppendToFile" value="true"/>
<rollingStyle value="Once" />
<rollingStyle value="Composite" />
<datePattern value=".yyyyMMdd-HH" />
<maxSizeRollBackups value="300" />
<maximumFileSize value="20MB" />
<Encoding value="UTF-8" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%utcdate{yyyy/MM/dd HH:mm:ss,fff} [%-5p] [%3t] %m%n" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="DEBUG" />
<levelMax value="FATAL" />
</filter>
</appender>
You can:
Use fileName="${basedir}/logs/${cached:${date:format=yyyy-MM-dd HH_mm_ss}}.log" as a way to ensure one log file per application instance.
Use archiveFileName="${archiveLogDirectory}/LogFile.log.{####}" to append numbers at the end (feel free to add or remove # as required, depending on your maxArchiveFiles).
Use archiveNumbering="Sequence" to achieve the order you want (higher numbers = newer logs).
Source: this piece of documentation and some personal experience.
Hopefully this basic example will help you getting closer to your final target:
<?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"
autoReload="true"
internalLogLevel="Error"
internalLogFile="./internal-nlog.txt"
throwExceptions="true">
<variable name="logDirectory" value="./logs"/>
<variable name="archiveLogDirectory" value="./logs/archive"/>
<targets>
<target name="errors"
xsi:type="File"
fileName="${logDirectory}/${cached:${date:format=yyyy-MM-dd HH_mm_ss}}.log"
archiveFileName="${archiveLogDirectory}/LogFile.log.{#}"
maxArchiveFiles="9"
archiveEvery="Hour"
archiveNumbering="Sequence"
/>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="errors"/>
</rules>
</nlog>
Not an expert on log4net, but it sounds like that rolingStyle="once" is the same as NLog FileTarget ArchiveOldFileOnStartup. So maybe something like this:
<nlog>
<variable name="EdgeAPILogPath" layout="${basedir}" />
<targets>
<target xsi:type="file" name="work"
fileName="${EdgeAPILogPath}/WebAPI_Work.log"
encoding="utf-8"
archiveNumbering="DateAndSequence"
archiveFileName="${EdgeAPILogPath}/WebAPI_Work.{#}.log"
archiveDateFormat="yyyyMMdd-HH"
archiveEvery="Hour"
archiveAboveSize="20000000"
archiveOldFileOnStartup="true"
maxArchiveFiles="300" />
</targets>
<rules>
<logger name="*" minLevel="Debug" writeTo="work" />
</rules>
</nlog>
See also: https://github.com/NLog/NLog/wiki/FileTarget-Archive-Examples
I've .net core application and I want to log user IP address who request for the api/performing action.
I used ${aspnet-request-ip} it doesn't log IP of client.
How to log IP?
Here is my 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"
autoReload="true"
internalLogLevel="Info"
internalLogFile="c:\temp\internal-nlog.txt">
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
<add assembly="NLog.Extensions.Logging"/>
<add assembly="NLog"/>
</extensions>
<variable name="ExceptionLayout" value="${longdate} [${processid}] ${uppercase:${level}} ${logger} ${environment-user} ${aspnet-request-ip} ${aspnet-request-url} ${aspnet-request-method} ${message}${exception:format=tostring,Stacktrace}"/>
<variable name="CommonLayout" value="${longdate} [${processid}] ${uppercase:${level}} ${logger} ${environment-user} ${aspnet-request-ip} ${message} "/>
<variable name ="logDir" value="${aspnet-appbasepath}\logs" />
<targets async="true">
<!-- write logs to file -->
<target xsi:type="File" name="file" layout="${CommonLayout}" fileName="${logDir}\log-${shortdate}.log" />
<target name="fileAsException"
xsi:type="FilteringWrapper"
condition="length('${exception}')>0">
<target xsi:type="File"
fileName="${logDir}\log-${shortdate}.log"
layout="${ExceptionLayout}" />
</target>
</targets>
<rules>
<logger name="*" writeTo="file,fileAsException">
<when condition="equals('${logger}','Elastic.Apm')" action="Ignore" />
</logger>
<logger name="Microsoft.*" maxlevel="Info" final="true" />
</rules>
</nlog>
here is startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
var authClient = new FusionAuthClient(apiKey: Configuration.GetSection("fusionAuth:apiKey").Value, host: Configuration.GetSection("fusionAuth:url").Value);
services.AddAuthorization(options =>
{
options.AddPolicy("finance", policy =>
{
policy.Requirements.Add(new TokenRequirement());
});
});
services.AddSingleton<IConfiguration>(Configuration);
services.AddSingleton<ILogger, Logger>();
}
here is log sample
2020-10-15 10:33:25.2828 [85588] DEBUG FinanceAPI.Program bhavin Application started
2020-10-15 10:33:27.4457 [85588] WARN HttpsRedirectionMiddleware bhavin Failed to determine the https port for redirect.
2020-10-15 10:33:27.9773 [85588] ERROR DeveloperExceptionPageMiddleware bhavin http://bhavin/favicon.ico GET An unhandled exception has occurred while executing the request.System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).
When I am trying to do logging from my code, like:
LogManager.GetCurrentClassLogger().Info($"{newAccounts.Count()} accounts addded.");
or
public ClientController(ILogger<ClientController> logger,
...
_logger.LogDebug("debug");
I got nothing in my log files. But I could see in my info.txt log file logs of internal asp.net actions, like:
2018-05-16 00:30:11.7482|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:63323/Controller/Method
My nlog.config looks like:
<targets>
<target name="fileLogDebug" xsi:type="File" fileName="${logDirectory}/mobileController.txt" />
<target name="fileLogTrace" xsi:type="File" fileName="${logDirectory}/trace.txt" />
<target name="fileLogDebug" xsi:type="File" fileName="${logDirectory}/debug.txt" />
<target name="fileLogInfo" xsi:type="File" fileName="${logDirectory}/info.txt" />
<target name="err" xsi:type="File" fileName="${logDirectory}/eeeeee.txt" />
</targets>
<rules>
<logger name="*" level="Trace" writeTo="fileLogTrace" />
<logger name="*" level="Debug" writeTo="fileLogDebug" />
<logger name="*" level="Info" writeTo="fileLogInfo" />
<logger name="*" level="Warn" writeTo="fileLogWarn" />
<logger name="*" level="Error" writeTo="err" />
<logger name="*" level="Fatal" writeTo="fileLogSecurity" />
</rules>
NLog init code is:
loggerFactory.AddNLog();
NLog.LogManager.LoadConfiguration("nlog.config");
app.AddNLogWeb();
Whats the problem?
Default log level for MS Logging is info.
So set MinimumLevel to Trace to control all from nlog.config:
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseNLog() // NLog: setup NLog for Dependency injection
.Build();
Example is from official wiki: https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2
I am trying to use Asyn log and Syn log in the same log4j2.xml file and want to set the root level is "INFO" and the specific mule package(org.mule) is "FATAL".but its automatically pick the info level for org.mule package and its not restricting the log level to specific package if i use sync and asynch level at same file. please help us if you have any idea. Thanks in advance.
Mule ESB - 3.6
<?xml version="1.0" encoding="utf-8"?>
<Configuration>
<Appenders>
<RollingFile name="file"
fileName="${sys:mule.home}${sys:file.separator}logs${sys:file.separator}eztutorial.log"
filePattern="${sys:mule.home}${sys:file.separator}logs${sys:file.separator}eztutorial-%i.log">
<PatternLayout pattern="%d [%t] %-5p %c - %m%n" />
<SizeBasedTriggeringPolicy size="10 MB" />
<DefaultRolloverStrategy max="10" />
</RollingFile>
</Appenders>
<Loggers>
<!-- CXF is used heavily by Mule for web services -->
<AsyncLogger name="org.apache.cxf" level="WARN" />
<!-- Apache Commons tend to make a lot of noise which can clutter the log -->
<AsyncLogger name="org.apache" level="WARN" />
<!-- Reduce startup noise -->
<AsyncLogger name="org.springframework.beans.factory"
level="WARN" />
<logger name="org.mule">
<level value="FATAL" />
</logger>
<logger name="com.mulesoft">
<level value="FATAL" />
</logger>
<category name="org.mule">
<priority value="FATAL" />
</category>
<category name="com.mulesoft">
<priority value="FATAL" />
</category>
<!-- Reduce DM verbosity -->
<AsyncLogger name="org.jetel" level="WARN" />
<AsyncLogger name="Tracking" level="WARN" />
<AsyncRoot level="INFO">
<AppenderRef ref="file" />
</AsyncRoot>
</Loggers>
</Configuration>
You can remove the <Category ...> entries from your config. (Log4j2 ignores them.)
For all named <Logger> and <AsyncLogger> entries, add additivity="false". Without this, the INFO level statements will still appear in your log because the root logger picks them up.
See http://logging.apache.org/log4j/2.x/manual/configuration.html#Additivity