LoggerName already in use - nlog

So i had this working, ive switched to paket and i guess some versions of dll's have changed.
However I still do not understand the error i am getting.
System.ArgumentException : LoggerName already in use
Parameter name: loggerName
my code is basically exactly as it is on here
http://www.tomdupont.net/2015/06/capture-xunit-test-output-with-nlog-and.html
public class NLogTests : IDisposable
{
private readonly ILogger _logger;
public NLogTests(ITestOutputHelper outputHelper)
{
_logger = outputHelper.GetNLogLogger();
}
public void Dispose()
{
_logger.RemoveTestOutputHelper();
}
[Fact]
public void Hello()
{
_logger.Trace("World Trace");
_logger.Debug("World Debug");
_logger.Warn("World Warn");
_logger.Error("World Error");
}
}
and config
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
throwExceptions="true">
<extensions>
<add assembly="xunit.NLog" />
</extensions>
<targets async="false">
<target xsi:type="TestOutput"
layout="${time}|${level:uppercase=true}|${logger}|${message}"
name="Test" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="Test" />
</rules>
</nlog>
The GetNLogLogger method has an overload that takes a logger name and a bool for incremental suffixes. Using these does not help.
I am really confused.
stacktrace:
System.ArgumentException
LoggerName already in use
Parameter name: loggerName
at Xunit.NLog.Targets.TestOutputTarget.Add(ITestOutputHelper testOutputHelper, String loggerName)
at Xunit.NLog.Helpers.TestOutputHelpers.AddTestOutputHelper(ITestOutputHelper testOutputHelper, String loggerName, Boolean addNumericSuffix)
at Xunit.NLogTestOutputExtensions.GetNLogLogger(ITestOutputHelper testOutputHelper, String loggerName, Boolean addNumericSuffix)
at ProjectRake.BusinessLogic.Spec.TautologiesToVerifyNLogOutput..ctor(ITestOutputHelper outputHelper) in M:\programming\ProjectRake\src\server\ProjectRake.BusinessLogic.Spec\TautologiesToVerifyNLogOutput.cs:line 19
edit:
have downgraded all xunit stuff to 2.1.0, same issue.

outputHelper.GetNLogLogger(); is calling AddTestOutputHelper("")
I guess it only works if you call it once.
You can use outputHelper.GetNLogLogger("myname"); or outputHelper.GetNLogLogger(typeof(NLogTests).Name);

Related

No assembly found containing a Startup or [AssemblyName].Startup class

I've tried resolving this from answers in other and similar posts, but no luck.
I'm Using MVC 5, framework 4.8 latest VS2017.
Thanks
My Config is: (including other attempts)
<configuration>
<appSettings>
<!--<add key="owin:AutomaticAppStartup" value="false" />-->
<add key="owin:HandleAllRequests" value="true"/>
<!--<add key="owin:AppStartup" value="Api.xxx" />-->
</appSettings>
</configuration>
Startup class is:
[assembly: OwinStartupAttribute(typeof(Api.xxx.Startup))]
namespace Api.xxx
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Allow all origins
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
….
}
}
}
and Api is:
namespace Api.xxx
{
[Route("values")]
public class ValuesController : ApiController
{
private static readonly Random _random = new Random();
public IEnumerable<string> Get()
{
var random = new Random();
return new[]
{
_random.Next(0, 10).ToString(),
_random.Next(0, 10).ToString()
};
}
}
}
I think you need to change
[assembly: OwinStartupAttribute(typeof(Api.xxx.Startup))]
to
[assembly: OwinStartup(typeof(Api.xxx.Startup))]
Reference: https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-startup-class-detection

Custom PatternLayoutConverter with log4net.Ext.Json?

I have the following log4net configuration:
<log4net>
<appender name="Console" type="log4net.Appender.ConsoleAppender">
<layout type='log4net.Layout.SerializedLayout, log4net.Ext.Json'>
<renderer type='log4net.ObjectRenderer.JsonDotNetRenderer, log4net.Ext.Json.Net'>
<DateFormatHandling value="IsoDateFormat" />
<NullValueHandling value="Ignore" />
</renderer>
<converter>
<name value="preparedMessage" />
<type value="JsonLogs.CustomLayoutConverter" />
</converter>
<default />
<remove value='message' />
<remove value='ndc' />
<member value='message:messageObject' />
<member value='details:preparedMessage' />
</layout>
</appender>
<appender name="Console2" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<converter>
<name value="preparedMessage" />
<type value="JsonLogs.CustomLayoutConverter" />
</converter>
<conversionPattern value="%level %thread %logger - %preparedMessage%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="Console" />
<appender-ref ref="Console2" />
</root>
</log4net>
with the following implementation of my custom PatternLayoutConverter:
namespace JsonLogs
{
using System.IO;
using log4net.Core;
using log4net.Layout.Pattern;
public class CustomLayoutConverter : PatternLayoutConverter
{
#region Methods
protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
{
if (loggingEvent.MessageObject is string stringMessage)
{
writer.Write(new { message = stringMessage });
}
else
{
writer.Write(loggingEvent.RenderedMessage);
}
}
#endregion
}
}
For some reason, the converter works perfectly fine with the Console2 appender(which is not JSON driven) but it doesn't work with the Console appender whose output is JSON.
Example of the output:
Console -> {"date":"2018-12-09T12:25:28.0529041+03:00","level":"INFO","appname":"JsonLogs.exe","logger":"JsonLogs.Program","thread":"1","message":"Test","details":"preparedMessage"}
Console2 -> INFO 1 JsonLogs.Program - { message = Test }
My goal is to have details always in JSON that's why I introduced my own converter to catch primitive values and wrap them in a custom object.
Is my configuration wrong? Or I'm missing something? Could you help me, please, to figure this out?
Thank you
The issue seems to be a bug of log4net.Ext.Json. I'm going to report it on their GitLab.
So far, I ended up with my custom log4net layout which looks like this
public class CustomLayout : PatternLayout
{
#region Public Methods and Operators
public override void Format(TextWriter writer, LoggingEvent loggingEvent)
{
var message = loggingEvent.MessageObject.GetType().IsPrimitive || loggingEvent.MessageObject is string || loggingEvent.MessageObject is decimal || loggingEvent.MessageObject is BigInteger
? new { message = loggingEvent.MessageObject }
: loggingEvent.MessageObject;
writer.WriteLine(JsonConvert.SerializeObject(new
{
timestamp = loggingEvent.TimeStampUtc,
threadId = loggingEvent.ThreadName,
details = message,
logger = loggingEvent.LoggerName,
level = loggingEvent.Level.DisplayName,
user = loggingEvent.UserName
}));
}
#endregion
}
it meets my needs and does exactly what I want.
The exact place of this problem is AddMember Method and its implementation. Here is SerializedLayout source code for that:
public virtual void AddMember(string value)
{
var arrangement = log4net.Util.TypeConverters.ArrangementConverter.GetArrangement(value, new ConverterInfo[0]);
m_arrangement.AddArrangement(arrangement);
}
As you can see the second parameter of GetArrangment is empty array of ConverterInfo, Though there must be our custom attached ones (by AddConverter method or by xml).
As the solution you can implement your own subclass that will derive from SerializedLayout with overridden AddMember like this:
public override void AddMember(string value)
{
var customConverter = new ConverterInfo("lookup", typeof(CustomPatternConverter));
var arrangement = log4net.Util.TypeConverters.ArrangementConverter.GetArrangement(value, new ConverterInfo[] { customConverter });
m_arrangement.AddArrangement(arrangement);
}
Hope it helps as it did with my case!

Use Java object in mule

I am using a java object which should return me an endpoint, then I want to invoke a service hosted at the specified endpoint. Please assist.
Below is my effort
In mule.xml
<spring:beans>
<spring:bean id="reqUrl" class="com.mule.sbus.drools.RequestUrl"
scope="singleton" />
</spring:beans>
<bpm:drools />
<http:listener-config name="NorthboundSingleEntrypoint"
host="0.0.0.0" port="8191" doc:name="HTTP Listener Configuration" />
<http:request-config name="HTTP_Request_Configuration"
host="acdc3a38cffc411e5a18606a62b4ee07-877599714.us-west-1.elb.amazonaws.com"
port="80" doc:name="HTTP Request Configuration" />
<flow name="sbusdroolsFlow">
<http:listener config-ref="NorthboundSingleEntrypoint"
path="/*" doc:name="HTTP" />
<set-variable variableName="requestUrl"
value="#[message.inboundProperties.'http.request.path']" doc:name="RequestUrl" />
<script:component doc:name="Script">
<script:script engine="groovy">
<![CDATA[
return requestUrl;
]]>
</script:script>
</script:component>
<bpm:rules rulesDefinition="routingRules.drl"
initialFacts-ref="reqUrl" />
<expression-transformer evaluator="groovy"
expression="message.getPayload().getObject()" doc:name="Expression" />
<logger message="#[groovy:message.getPayload().getObject()]" level="INFO"
doc:name="LoggerResp" />
</flow>
Below is my drools .drl
#default dialect for the semantic code will be MVEL
global org.mule.module.bpm.MessageService mule;
import com.mule.sbus.drools.RequestUrl
dialect "mvel"
declare RequestUrl
#role(event)
end
rule "test123"
lock-on-active
when
$url:RequestUrl(url=="test123")
then
#order.setDestination("WAREHOUSE_A");
modify($url){setEndPoint("test123")}
end
rule "test234"
lock-on-active
when
$url:RequestUrl(url=="test234")
then
#order.setDestination("WAREHOUSE_A");
modify($url){setEndPoint("test234")}
end
and my java class
package com.mule.sbus.drools;
public class RequestUrl {
private String url;
private String endPoint;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getEndPoint() {
return endPoint;
}
public void setEndPoint(String endPoint) {
/*if(endPoint=="test123")
this.endPoint = endPoint;
else*/
this.endPoint = "/checkcibil";
System.out.println("inside java :::: " + endPoint);
}
#Override
public String toString() {
// TODO Auto-generated method stub
return "url : " + url + " endPoint : " + endPoint;
}
}
As you can see I am invoking my setter from the drools file and once I get the string I want to print the same using
<logger message="#[groovy:message.getPayload().getObject()]" level="INFO"
doc:name="LoggerResp" />
but I don't know what should be the message value to use. Please assist
Got the answer,
As I am using groovy, have commented drools, and the updated the code as below
<script:component doc:name="Script">
<script:script engine="groovy">
<![CDATA[
reqUrl.setEndPoint(requestUrl);
String endpnt = reqUrl.getEndPoint();
message.setProperty('endpnt', endpnt,org.mule.api.transport.PropertyScope.INVOCATION);
]]>
</script:script>
</script:component>
<logger message="#[flowVars['endpnt']]" level="INFO" doc:name="LoggerResp" />
Using groovy I am invoking the setter and the call the getter to have the value in endpt variable. This can now be set as a property in the message and later we can retrieve the same (outside groovy script tags), using #[flowVars['endpnt']]

Can't get NLog to work

I am having no luck getting NLog to work. Working through the tutorial, I have the exact code as seen there.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;
namespace NLog2
{
class Program
{
static void Main(string[] args)
{
var c = new MyClass();
c.MyMethod1();
}
}
public class MyClass
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public void MyMethod1()
{
logger.Trace("Sample trace message");
logger.Debug("Sample debug message");
logger.Info("Sample informational message");
logger.Warn("Sample warning message");
logger.Error("Sample error message");
logger.Fatal("Sample fatal error message");
// alternatively you can call the Log() method
// and pass log level as the parameter.
logger.Log(LogLevel.Info, "Sample fatal error message");
}
}
}
My config file (named NLog.config) looks like...
<?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="logfile" xsi:type="File" fileName="file.txt" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile" />
</rules>
</nlog>
I get no output. Can someone see what the issue is here?
Web User, find your NLog.config in uour files list in Solution Explorer. Right click NLog.config and choose properties. choose "Copy always" at "Copy to output directory" and be happy ^)
Dumb mistake. I had not set the config file to copy to the output directory.

Nlog Logger.Info not working

i have a webservice which is consumed via jquery ... now the problem is i want to put some debug into from nlog so that i can see how the flow is actually going .. i thought nlog's option for debuging ....
here is my config and code
<targets>
<target name="file" xsi:type="File"
layout="${longdate} ${logger} ${message}"
fileName="${basedir}/Logs/${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="file" />
<logger name="*" minlevel="Error" writeTo="file" />
<logger name="*" minlevel="Fatal" writeTo="file" />
<logger name="*" minlevel="Info" writeTo="file" />
</rules>
and the logger class where i have given for getting debug information is
[ScriptService]
public class Service : System.Web.Services.WebService
{
Logger logger = LogManager.GetCurrentClassLogger();
[WebMethod]
public String GetAgentDetails(String AgentId)
{
logger.Info("This is webservice");
String result = string.Empty;
try
{
using (ISession session = NhibernateHelper.Opensession())
{
logger.Info("Enters Session");
var agent = GetAgent(); // Gets the agent object
result = JsonConvert.SerializeObject(agent);
logger.Info(result);
return result;
}
}
catch (InvalidOperationException ioe)
{
logger.Error(ioe.Message);
logger.Fatal(ioe.Message);
logger.Error(ioe.InnerException);
logger.Fatal(ioe.InnerException);
return null;
}
catch (Exception ex)
{
logger.Error(ex.Message);
logger.Fatal(ex.Message);
logger.Error(ex.InnerException);
logger.Fatal(ex.InnerException);
}
return result;
}
}
when accessed through the jquery script it should have written the log informations where i have written logger.info(result) but it seems no log file is created .can someone explain whats the problem ? however the same log file works for all other classes . no issues in that . if exceptions are thrown the log file gets created and log is written. but in this case for logger.info its not happening . i am using Nlog 2.0 with Asp.net 3.5 SP1 .

Resources