Log4Net - Loggly does not send error logs - c#

I'm trying to setup loggly with a C# projet by following the Loggly tutorial but it doesn't work.
I've added the log4net-loggly nuget package
I've add the following code in my app.config :
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="LogglyAppender" />
</root>
<appender name="LogglyAppender" type="log4net.loggly.LogglyAppender, log4net-loggly">
<rootUrl value="https://xxxxx.loggly.com/" />
<inputKey value="XXXXX" />
<tag value="log4net" />
</appender>
</log4net>
And this is how I'm trying to send logs to Loggly :
var logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
logger.Error("your log message", new Exception("your exception message"));
I've debugged with Fiddler to see if there was a request to Loggly but there is nothing.
What am I missing ?

install the Microsoft.CSharp package in your solution. This library is necessary to use the C# dynamic data types.

Related

Write log-file when testing with NUnit

I have a test-assembly (MyTestProject) where I want to write some logging using log4net. Thus I created a config-file with the same name as the assembly where I set up the logging as suggested here:
<?xml version="1.0" encoding="utf-8" ?>
<!-- .NET application configuration file
This file must have the exact same name as your application with
.config appended to it. For example if your application is testApp.exe
then the config file must be testApp.exe.config it must also be in the
same directory as the application. -->
<configuration>
<configSections>
<!-- Register the section handler for the log4net section -->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
<sectionGroup name="NUnit">
<!-- For .NET 2.0 Beta 2 replace the lines with the following -->
<section name="TestCaseBuilder" type="System.Configuration.NameValueSectionHandler, System, Version=2.0.50215.44, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="TestRunner" type="System.Configuration.NameValueSectionHandler, System, Version=2.0.50215.44, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</sectionGroup>
</configSections>
<NUnit>
<TestCaseBuilder>
<add key="OldStyleTestCases" value="false" />
</TestCaseBuilder>
<TestRunner>
<!-- Valid values are STA,MTA. Others ignored. -->
<add key="ApartmentState" value="STA" />
<!-- See ThreadPriority enum for other valid values -->
<add key="ThreadPriority" value="Normal" />
</TestRunner>
</NUnit>
<appSettings>
<add key="ApartmentState" value="STA" />
<add key="apartment" value="STA" />
</appSettings>
<!-- This section contains the log4net configuration settings -->
<log4net debug="true">
<!-- Define some output appenders -->
<appender name="LogFileAppender" type="log4net.Appender.FileAppender,log4net" >
<param name="File" value="D:/data.log" />
<param name="AppendToFile" value="false" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] <%X{auth}> - %m%n" />
</layout>
</appender>
<!-- Setup the root category, add the appenders and set the default priority -->
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
</configuration>
Within my code I set up the logging as follows:
[TestFixture]
public class MyTest
{
private readonly ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
[TestFixtureSetUp]
public void Init()
{
log.Info("Something to log");
...
}
}
However when I run my tests no such file D:/data.log is created. Even more suspicious when I debug the code and add a watch to the appenders from log I get an empty collection.
I post this together as it stuck me for hours.
I looked into the directory where the file should stay, there was one (apperently from an earlier test-run as its timestamp was not recent). Trying to delete the file got me a message that it is currently in use from nunit-agent-x86.exe. So I killed the process in TaskManager and re-run my tests. Now everything works correct and I get my logging into the file.
This Could have been solved if you give value for key, AppendToFile as true..
As logger appends logging to the existing file and wont try to delete it.

Log4net - Does not create a log file

I'm using log4net in order to create a log, but it doesn't do anything.
Here is the app.config:
<?xml version="1.0" encoding="utf-8">
<configuration>
<configSection>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSection>
<log4net>
<appender name="WriteToFile" type="log4net.Appender.FileAppender">
<file value="log.txt" />
<layout ="log4net.Layout.SimpleLayout" />
</appender>
<root>
<level value="ALL" />
<appender-ref ref="WriteToFile"/>
</root>
</log4net>
</configuration>
I have the following line in AssemblyInfo.cs:
[assembly: log4net.Config.XmlConfigur(ConfigFile ="App.config", Watch= true)]
Here is an attempt to write to the file:
private static readonly ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public void write()
{
log.Info("Some text here");
}
And the following line:
log4net.Config.XmlConfigurator.Configure();
If this is an executable I suppose that your config file is not called App.config at the resulting bin folder but rather MyApp.exe.config. So you may try fixing this:
ConfigFile ="App.config"
You can also skip the config file name if you are using the default:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
Also make sure that the account you are running your application under has write permission to the folder in which you expect the log file to be written.
UPDATE:
Step by step guide:
Create a new Console Application
Install the log4net NuGet
Use the following in your App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="WriteToFile" type="log4net.Appender.FileAppender">
<file value="log.txt" />
<layout type="log4net.Layout.SimpleLayout" />
</appender>
<root>
<level value="ALL" />
<appender-ref ref="WriteToFile" />
</root>
</log4net>
</configuration>
And in your Program.cs:
using log4net;
using System.Reflection;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace ConsoleApplication1
{
class Program
{
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static void Main(string[] args)
{
log.Info("Some text here");
}
}
}
I have only been successful with log4net when I ran the static Configure method:
log4net.Config.XmlConfigurator.Configure();
Wrapping it in one method below read default config for the application, be it web.config or app.config:
private static void InitLogging()
{
log4net.Config.XmlConfigurator.Configure();
_logger = Common.Logging.LogManager.GetLogger(typeof(Program));
_logger.Debug("Logging initialized");
}
It seems more elegant with an decorator attribute the way you are suggesting, but the above mentioned may be worth a try.

GetAppenders() returns empty list in log4net

I have the following method that fetches the name of the log file in log4net:
private string GetLogFile()
{
var repo = LogManager.GetRepository();
var fileAppender = repo.GetAppenders()
.OfType<FileAppender>().Single(fa => fa.Name == "LogFileAppender");
var logFile = fileAppender != null ? fileAppender.File : string.Empty;
return logFile;
}
This code works fine when I have this code running in a Windows service. But I was given the task to move logging to the main web app. So I referenced log4net in the web app, moved over the config settings, etc. But now when I run the same code the call to GetAppenders() returns an empty list.
Here is the config I have:
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="\\MYSERVER\Temp\MYFiles\Log\Log.txt" />
<param name="AppendToFile" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
Is there an extra step in the web app version that I need to do?
It turned out to be something missing in the Global.asax.cs file in the Application_Start method. I needed to add the following line:
log4net.Config.XmlConfigurator.Configure();
You are required to also call out the additional config sections at the top of the file, as such:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
</configSections>
As well as the addition of the following above your log4net element:
<common>
<logging>
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net">
<arg key="configType" value="INLINE" />
</factoryAdapter>
</logging>
</common>
This makes the assumption that you're using Common.Logging and that you are not using a standalone config file (meaning the configuration is within the web.config).

Configuring/Installing log4net for RavenDB in Visual Studio 2010

I'm trying to configure my C# project to use log4net for RavenDB. I already have log4net working with a FileAppender, but the RavenAppender doesn't seem to be working right now. The following are the steps I have taken so far:
Step 1: Installing log4net.Raven
I installed the log4net.Raven library using the following NuGet Package Manager console instructions (taken from the package website linked to above):
Install-Package log4net.Raven
That command added the log4net.Raven library to my project references.
Step 2: Configuring Web.config
In my Web.config file, I have the following settings, most of which are copy and pasted from the README file for the log4net.Raven project on GitHub (the owner of log4net.Raven also has similar configuration settings published on his blog):
<!-- Example connection string config from blog -->
<configsections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net">
</configsections>
<connectionstrings>
<add connectionstring="Url=http://raven; DefaultDatabase=Log" name="RavenLogs">
<add connectionstring="Url=http://localhost:8080;user=asa;password=asa" name="SecureRaven">
</add>
</add>
</connectionstrings>
<!-- My current config -->
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<connectionStrings>
<add name="RavenDB" connectionString="Url=http://localhost:8080;Database=MyDatabase" />
</connectionStrings>
<!-- Example log4net config from README.
My project uses these settings except for the connectionString value,
which is set to "RavenDB" to match the setting name above.
-->
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<!-- LogFileAppender settings here -->
</appender>
<appender name="RavenAppender" type="log4net.Raven.RavenAppender">
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
<connectionString value="RavenDB"/>
<maxNumberOfRequestsPerSession value="100"/>
<bufferSize value="50" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="ERROR" />
</evaluator>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="LogFileAppender" />
<appender-ref ref="RavenAppender" />
</root>
</log4net>
Step 3: Logging from C# code
In my C# code, I have the following:
public class FooController : Controller
{
private static ILog _log = LogManager.GetLogger(typeof(FooController));
public ActionResult Index()
{
_log.Info("Hello World!");
return View("Index");
}
}
That code will write out to a log file on my workstation, so from that I know that log4net in general is working correctly. But for RavenDB, I've been checking the Documents and Logs for MyDatabase through the Raven studio in a web browser, and I do not see any Info level log with the message "Hello World".
Does anyone have any ideas of what the problem could be and how to fix it?
May be the problem is here:
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
if you don't have class named FileAppender in your project you need to add the library name where FileAppender is, for example:
<appender name="LogFileAppender"
type="log4net.Appender.FileAppender, log4net.Raven">
(the syntax for type is =" Fully qualified class name , assembly file name , version , culture , public key token ")
Try debug log4net as here Log4Net Troubleshooting
If you find this line:
log4net: Adding appender named [RavenAppender] to logger [root].
RavenAppender is working

Spring.Net logging with Log4Net not working

I'm having trouble getting Spring.Net to log, using Log4Net. I'm particulary interested in seeing logging around the Aspects. I'm using a pretty simple log config, similar to that of the MovieFinder example app:
...
<logger name="Spring">
<level value="DEBUG" /> <!-- Have tried INFO as well, no different -->
<appender-ref ref="SpringAppender"/>
</logger>
<appender name="SpringAppender" type="log4net.Appender.RollingFileAppender">
<file value="..\Log\Spring_Log.txt"/>
<appendToFile value="true"/>
<maximumFileSize value="100MB"/>
<maxSizeRollBackups value="2"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level [%thread] %logger - %message%newline"/>
</layout>
</appender>
...
The file "Spring_Log.txt" is created, but nothing is logged to it (i.e. empty file). Log4Net is currently logging correctly for NHibernate and our custom app logging. I'm using Spring.Net v1.2.0.20313 and Log4Net v1.2.10.0.
Has anybody else had this problem that they were able to resolve? Many thanks for any help, cheers.
As Erich said, you need to configure Common.Logging.
Your log4net configuration file is fine. Here is what I’ve got using your configuration file:
2009-05-02 19:08:40,890 DEBUG [10] Spring.Objects.Factory.Support.AbstractObjectDefinitionReader - Loading XML object definitions from config [C:\Documents and Settings\pczapla\My Documents\Visual Studio 2008\Projects\TimeLogger\TimeLogger\bin\Debug\TimeLogger.exe.config#spring/objects]
2009-05-02 19:08:40,905 DEBUG [10] Spring.Objects.Factory.Support.AbstractObjectDefinitionReader - Using the following XmlReader implementation : System.Xml.XsdValidatingReader
2009-05-02 19:08:40,921 DEBUG [10] Spring.Objects.Factory.Xml.DefaultObjectDefinitionDocumentReader - Loading object definitions.
2009-05-02 19:08:40,921 DEBUG [10] Spring.Objects.Factory.Xml.ObjectDefinitionParserHelper - Loading object definitions...
Here is a quick guide how to configure Common.Logging:
Add Common.Logging & Common.Logging.Log4Net assemblies they are shipped with spring in lib folder (C:\Program Files\Spring.NET 1.2.0\lib\Net\2.0\).
Then Add the following configuration to your app.config:
<configuration>
</configSections>
...
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
</configSections>
...
<common>
<logging>
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net">
<!-- Common Logging assumes that log4net is initialized -->
<arg key="configType" value="EXTERNAL"/>
<!-- Or it can configure log4net for you
<arg key="configType" value="FILE-WATCH" />
<arg key="configFile" value="path\to\your\log4net.config" />
-->
</factoryAdapter>
</logging>
</common>
</configuration>
That is it. Now you should get debug messages from spring.
Spring.NET uses Common.Logging. Did you configure Common.Logging to log to log4net? See http://netcommon.sourceforge.net/documentation.html for the documentation
hth,
Erich

Categories