Why I can't save logging to database via NLog? - asp.net-core

Why I can't save logging to database via NLog? Then I save to file is working perfectly, but to database not.
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">
<targets>
<target name="alllogs" xsi:type="File" fileName="C:\Users\Artyrik\Desktop\RVT\RVT_Administrator\RVT_Administrator\file.txt" />
<target name="database" xsi:type="Database" connectionString="Server=DESKTOP-GDI15RS\\SQLEXPRESS;Database=RVTLogs;Trusted_Connection=True;MultipleActiveResultSets=true"
commandText="insert into dbo.Administrator (
MachineName, Logged, Level, Message,
Logger, Callsite, Exception
) values (
#MachineName, #Logged, #Level, #Message,
#Logger, #Callsite, #Exception
);">
<parameter name="#MachineName" layout="${machinename}" />
<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}" />
<parameter name="#Exception" layout="${exception:tostring}" />
</target>
</targets>
<rules>
<!--<logger name="Admin" minlevel="Trace" writeTo="alllogs" />
<logger name="User" minlevel="Trace" writeTo="alllogs" />-->
<logger name="AdminLog" minlevel="Trace" writeTo="database" />
</rules>
</nlog>
Implement in a Class:
```
private static Logger _nLog = LogManager.GetLogger("AdminLog");
_nLog.Info(data.IP + " tried to auth.");```

You need to add internalLogFile parameter to your nlog tag. You will have an internal log and see what is wrong with your configuration if an error occured :
<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">

Related

NLog prevents update database in ASP.NET Core

I'm using NLog in my ASP.NET Core Web API project.
I have and issue in Update-Database while using NLog
This is my NLog.Config file in my application :
<?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"
throwExceptions="true"
internalLogLevel="Trace"
internalLogFile="C:\Nlog\logs\internalLog.txt">
<targets>
<target xsi:type="Database"
name="dbTarget"
connectionString="${configsetting:item=ConnectionStrings.DefaultConnection}"
commandText="INSERT INTO [app].[TblApplicationLog](Logged,Message,Level,Exception,Logger,Url,UserName,ServerName,Ip,Controller,Action,Host,Application,Callsite,UserAuthenticated, Useragent)
VALUES (#datetime,#msg,#level,#exception,#logger,#url,#username,#servername,#ip,#controller,#action,#host,#application,#callsite,#userAuthenticated,#useragent)">
<parameter name="#application" layout="AspNetCoreNlog" />
<parameter name="#datetime" layout="${date}" />
<parameter name="#msg" layout="${message}" />
<parameter name="#level" layout="${level}" />
<parameter name="#exception" layout="${exception:innerFormat=Message,StackTrace}" />
<!--<parameter name="#trace" layout="${stacktrace}" />-->
<parameter name="#callsite" layout="${callsite}" />
<parameter name="#logger" layout="${logger}" />
<parameter name="#url" layout="${aspnet-request-url}" />
<parameter name="#username" layout="${aspnet-user-identity}" />
<parameter name="#servername" layout="${machinename}" />
<parameter name="#ip" layout="${aspnet-request-ip}" />
<parameter name="#controller" layout="${aspnet-mvc-controller}" />
<parameter name="#action" layout="${aspnet-mvc-action}" />
<parameter name="#host" layout="${aspnet-request-host}" />
<parameter name="#useragent" layout="${aspnet-request-useragent}" />
<parameter name="#userAuthenticated" layout="${aspnet-user-isauthenticated}" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="dbTarget" />
</rules>
</nlog>
Everything in logging works fine but if I add a new migration and wanna do update-database, I get following error in NuGet Package Manager Console:
An error occurred while writing to logger(s). (Timeout expired. The
timeout period elapsed prior to completion of the operation or the
server is not responding.)
Note: When I exclude the Nlog.config file from my solution, Update-Database works fine like always, but with including Nlog.config file in my solution, Update-database won't work anymore
My mistake was from this line of code in my NLog.Conif file
in line number 5 = throwException="true"
After I removed this line, update database done

Is there any similar kind of configure to rolingStyle="once" of log4net is available for 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

NLog.Web.AspNetCore layout renderers are empty

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

OrientDB Cluster Configuration Using VM

I am trying to form a orientDB cluster using orientdb-enterprise-2.2.3 using the VM hosted on local server. The VM have the configuration of Fedora OS 18. I have attached the orientdb-server-config.xml and hazelcast.xml file.
orientdb-server-config.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<orient-server>
<handlers>
<handler class="com.orientechnologies.orient.graph.handler.OGraphServerHandler">
<parameters>
<parameter value="true" name="enabled"/>
<parameter value="50" name="graph.pool.max"/>
</parameters>
</handler>
<handler class="com.orientechnologies.orient.server.hazelcast.OHazelcastPlugin">
<parameters>
<parameter value="${distributed}" name="enabled"/>
<parameter value="${ORIENTDB_HOME}/config/default-distributed-db-config.json" name="configuration.db.default"/>
<parameter value="${ORIENTDB_HOME}/config/hazelcast.xml" name="configuration.hazelcast"/>
</parameters>
</handler>
<handler class="com.orientechnologies.orient.server.handler.OJMXPlugin">
<parameters>
<parameter value="false" name="enabled"/>
<parameter value="true" name="profilerManaged"/>
</parameters>
</handler>
<handler class="com.orientechnologies.orient.server.handler.OAutomaticBackup">
<parameters>
<parameter value="false" name="enabled"/>
<parameter value="${ORIENTDB_HOME}/config/automatic-backup.json" name="config"/>
</parameters>
</handler>
<handler class="com.orientechnologies.orient.server.handler.OServerSideScriptInterpreter">
<parameters>
<parameter value="true" name="enabled"/>
<parameter value="SQL" name="allowedLanguages"/>
</parameters>
</handler>
</handlers>
<network>
<sockets>
<socket implementation="com.orientechnologies.orient.server.network.OServerTLSSocketFactory" name="ssl">
<parameters>
<parameter value="false" name="network.ssl.clientAuth"/>
<parameter value="config/cert/orientdb.ks" name="network.ssl.keyStore"/>
<parameter value="password" name="network.ssl.keyStorePassword"/>
<parameter value="config/cert/orientdb.ks" name="network.ssl.trustStore"/>
<parameter value="password" name="network.ssl.trustStorePassword"/>
</parameters>
</socket>
<socket implementation="com.orientechnologies.orient.server.network.OServerTLSSocketFactory" name="https">
<parameters>
<parameter value="false" name="network.ssl.clientAuth"/>
<parameter value="config/cert/orientdb.ks" name="network.ssl.keyStore"/>
<parameter value="password" name="network.ssl.keyStorePassword"/>
<parameter value="config/cert/orientdb.ks" name="network.ssl.trustStore"/>
<parameter value="password" name="network.ssl.trustStorePassword"/>
</parameters>
</socket>
</sockets>
<protocols>
<protocol implementation="com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary" name="binary"/>
<protocol implementation="com.orientechnologies.orient.server.network.protocol.http.ONetworkProtocolHttpDb" name="http"/>
</protocols>
<listeners>
<listener protocol="binary" socket="default" port-range="2424-2430" ip-address="0.0.0.0"/>
<listener protocol="http" socket="default" port-range="2480-2490" ip-address="0.0.0.0">
<commands>
<command implementation="com.orientechnologies.orient.server.network.protocol.http.command.get.OServerCommandGetStaticContent" pattern="GET|www GET|studio/ GET| GET|*.htm GET|*.html GET|*.xml GET|*.jpeg GET|*.jpg GET|*.png GET|*.gif GET|*.js GET|*.css GET|*.swf GET|*.ico GET|*.txt GET|*.otf GET|*.pjs GET|*.svg GET|*.json GET|*.woff GET|*.woff2 GET|*.ttf GET|*.svgz" stateful="false">
<parameters>
<entry value="Cache-Control: no-cache, no-store, max-age=0, must-revalidate\r\nPragma: no-cache" name="http.cache:*.htm *.html"/>
<entry value="Cache-Control: max-age=120" name="http.cache:default"/>
</parameters>
</command>
<command implementation="com.orientechnologies.orient.graph.server.command.OServerCommandGetGephi" pattern="GET|gephi/*" stateful="false"/>
</commands>
<parameters>
<parameter value="utf-8" name="network.http.charset"/>
<parameter value="true" name="network.http.jsonResponseError"/>
</parameters>
</listener>
</listeners>
</network>
<storages/>
<users>
<user resources="*" password="root" name="root"/>
<user resources="connect,server.listDatabases,server.dblist" password="guest" name="guest"/>
</users>
<properties>
<entry value="1" name="db.pool.min"/>
<entry value="50" name="db.pool.max"/>
<entry value="true" name="profiler.enabled"/>
</properties>
<isAfterFirstTime>true</isAfterFirstTime>
</orient-server>
hazelcast.xml
<?xml version="1.0" encoding="UTF-8"?>
<hazelcast xsi:schemaLocation="http://www.hazelcast.com/schema/config hazelcast-config-3.3.xsd"
xmlns="http://www.hazelcast.com/schema/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<group>
<name>orientdb</name>
<password>orientdb</password>
</group>
<network>
<port auto-increment="true">2434</port>
<join>
<multicast enabled="true">
<multicast-group>235.1.1.1</multicast-group>
<multicast-port>2434</multicast-port>
</multicast>
</join>
</network>
<executor-service>
<pool-size>16</pool-size>
</executor-service>
</hazelcast>
But the two nodes are not getting connected in the cluster. I am trying the multicast join for clustering. The individual servers are working fine.
What might be the issue with the multicast clustering?
Hi Deep Mistry try iptables firewall configuration as the ports might be blocked by firewall

FitNesse integration with CCNet, correct XML in the build log?

I am almost there with my fitnesse to ccnet integration, but my results aren't showing up in my dashboard despite following this:
http://confluence.public.thoughtworks.org/display/CCNET/Using+CruiseControl.NET+with+FitNesse
I have merged my xml result file using the File Merge Task, that I generated using this:
Parse Fitnesse RESTFul XML output into TFS Test format
In the XML below, is the xml the way it should be? This is my logfile from ccnet webdashboard:
<cruisecontrol project="MagnusTest">
<request source="KDP021368" buildCondition="ForceBuild">Build (ForceBuild) triggered from KDP021368</request>
<parameters>
<parameter name="$CCNetArtifactDirectory" value="C:\Program Files\CruiseControl.NET\server\MagnusTest\Artifacts" />
<parameter name="$CCNetBuildCondition" value="ForceBuild" />
<parameter name="$CCNetBuildDate" value="2011-05-05" />
<parameter name="$CCNetBuildTime" value="14:36:44" />
<parameter name="$CCNetFailureUsers" value="System.Collections.ArrayList" />
<parameter name="$CCNetIntegrationStatus" value="Unknown" />
<parameter name="$CCNetLabel" value="7" />
<parameter name="$CCNetLastIntegrationStatus" value="Success" />
<parameter name="$CCNetListenerFile" value="C:\Program Files\CruiseControl.NET\server\MagnusTest\Artifacts\MagnusTest_ListenFile.xml" />
<parameter name="$CCNetModifyingUsers" value="System.Collections.ArrayList" />
<parameter name="$CCNetNumericLabel" value="7" />
<parameter name="$CCNetProject" value="MagnusTest" />
<parameter name="$CCNetProjectUrl" value="http://KDP021368/ccnet" />
<parameter name="$CCNetRequestSource" value="KDP021368" />
<parameter name="$CCNetUser" value="" />
<parameter name="$CCNetWorkingDirectory" value="C:\Program Files\CruiseControl.NET\server\MagnusTest\WorkingDirectory" />
</parameters>
<modifications />
<integrationProperties>
<CCNetArtifactDirectory>C:\Program Files\CruiseControl.NET\server\MagnusTest\Artifacts</CCNetArtifactDirectory>
<CCNetBuildCondition>ForceBuild</CCNetBuildCondition>
<CCNetBuildDate>2011-05-05</CCNetBuildDate>
<CCNetBuildTime>14:36:44</CCNetBuildTime>
<CCNetFailureUsers />
<CCNetIntegrationStatus>Success</CCNetIntegrationStatus>
<CCNetLabel>7</CCNetLabel>
<CCNetLastIntegrationStatus>Success</CCNetLastIntegrationStatus>
<CCNetListenerFile>C:\Program Files\CruiseControl.NET\server\MagnusTest\Artifacts\MagnusTest_ListenFile.xml</CCNetListenerFile>
<CCNetModifyingUsers />
<CCNetNumericLabel>7</CCNetNumericLabel>
<CCNetProject>MagnusTest</CCNetProject>
<CCNetProjectUrl>http://KDP021368/ccnet</CCNetProjectUrl>
<CCNetRequestSource>KDP021368</CCNetRequestSource>
<CCNetWorkingDirectory>C:\Program Files\CruiseControl.NET\server\MagnusTest\WorkingDirectory</CCNetWorkingDirectory>
<LastIntegrationStatus>Success</LastIntegrationStatus>
<LastSuccessfulIntegrationLabel>7</LastSuccessfulIntegrationLabel>
<LastModificationDate>04.05.2011 14:36:46</LastModificationDate>
</integrationProperties>
<build date="2011-05-05 14:36:44" buildtime="00:00:01" buildcondition="ForceBuild">
<msbuild startTime="05/05/2011 14:36:45" elapsedTime="00:00:01" elapsedSeconds="1" success="true">
<project name="FitnesseTest" file="M:\magnufu_PCtcGbad1_Test\CtcGbad1_pres\BuildAllComponents.proj" startTime="05/05/2011 14:36:46" elapsedTime="00:00:00" elapsedSeconds="0" success="true">
<target name="FitnesseTest" startTime="05/05/2011 14:36:46" elapsedTime="00:00:00" elapsedSeconds="0" success="true">
<message level="high"><![CDATA[echo Dette er BuildAllComponents.proj]]></message>
<message level="high"><![CDATA[Dette er BuildAllComponents.proj]]></message>
</target>
</project>
</msbuild>
<SummaryResult>
<TestName>TestSmoke</TestName>
<TestResult>Failed</TestResult>
<ErrorMessage>6 right, 3 wrong, 0 ignores and 2 exceptions.
</ErrorMessage>
<InnerTests>
<InnerTest>
<TestName>TestSmoke</TestName>
<TestResult>Failed</TestResult>
<ErrorMessage>6 right, 3 wrong, 0 ignores and 2 exceptions.
</ErrorMessage>
</InnerTest>
</InnerTests>
</SummaryResult></build>
</cruisecontrol>
So why arent my results showing up in the dashboard? I have edited my dashboard.config to include:
<xslReportBuildPlugin description="Fitnesse Report" actionName="FitnesseReport" xslFileName="xsl\fitnesse.xsl"/>
and I get the XML in my build log.
Thank You!
Cheers