I use log4net for logging errors in my project. I want to log messages into DB (SQL Server) so I added AdoNetAppender but it does not work (other appenders work fine, connection string is correct).
What can be wrong?
I decided to create a bare-bones example project. This works. Perhaps you should try making it work.
Create an empty console application project. Add a reference to log4net.
C# Code:
using log4net;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace Litter
{
class Program
{
static void Main()
{
LogManager.GetLogger("default").Info("Hello, World!");
}
}
}
Config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<log4net>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1"/>
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<connectionString value="data source=localhost\sqlexpress;initial catalog=Litter;integrated security=True;"/>
<commandText value="INSERT INTO Logs ([Message]) VALUES (#message)"/>
<parameter>
<parameterName value="#message"/>
<dbType value="String"/>
<size value="2000"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message"/>
</layout>
</parameter>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="AdoNetAppender"/>
</root>
</log4net>
</configuration>
Database table:
CREATE TABLE [dbo].[Logs]([Message] [nvarchar](2000) NOT NULL)
GO
That's about as simple as it gets. If you can make this work, then I'd start looking very closely at your app's AdoNetAppender configuration.
Thank you all. The problem was in DB. I just have to set the RowGuid property as true.
Related
I have a class library that performs a routine needed for installation. From everything I have researched, I believe I have things set up correctly. However, the routine absolutely will not log anything. Here is what I have:
I have added the class library project as a reference to the host project.
In my class library, I have the following:
private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public InstallDLL() {
Log.Error("Where are you goinng?");
}
In the host application, I have added the following line to the AssemblyInfo.cs class: [assembly: log4net.Config.XmlConfigurator(Watch = true)]
Finally, this is the content of my app.config file:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>
<log4net>
<appender name="TestAppender" type="log4net.Appender.RollingFileAppender" >
<file value=".\Log Directory\MyTestAppender.log" />
<encoding value="utf-8" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="2MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%M %C] - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<!-- If the following line is not included the log file will not be created even if log4net is configured with this file. -->
<appender-ref ref="TestAppender" />
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
I have to be missing something, but what? Keep in mind that logging works fine from the host application...
**** EDIT ********************************************************************
I think I may know what is going on here. The .dll file produced by this project runs BEFORE the host project runs because it is part of the installation script. I think the host project has to run first to initialize the log4net configurations. When I call the method in the .dll file FROM the host application, and not from the installer package, the log4net logging works just fine. Does anyone know if this is root cause, and how I can get around this?
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />, Can you check your Target Framework in Assembly properties?
I just compared with my config file, I have this <log4net debug="true">. Could you please add this?
Below codes make log file Formatted Datetime(e.g.: yyyyMMdd_HHmmss.log)
But there are problems with the results.* * I want to make only one log file When I run the code below * * * * but, two or more log files created.* *
(e.g.: 20170721_14 * * 22 * * 30.log, 20170721_14 * * 23 * * 00.log, 20170721.....)
i don 't know reason why
i want to solve my problem
How do I fix my code ?
C# Code:
namespace ConsoleApplication1
{
class Program
{
static readonly ILog Logger = LogManager.GetLogger("DebugLogger");
static void Main(string[] args)
{
int i;
for (i=1;i<=50000000;i++)
Logger.DebugFormat("{0},{1},{2}", 999, 997, 996);
}
}
}
my web.config as below:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="DebugAppender" type="log4net.Appender.RollingFileAppender">
<file value=""/>
<datePattern value="yyMMdd_HHmmss'.log '" />
<staticLogFileName value="false" />
<appendToFile value="false" />
<rollingStyle value="Date"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message%newline">
</conversionPattern>
</layout>
</appender>
<logger name="DebugLogger">
<level value="ALL" />
<appender-ref ref="DebugAppender" />
</logger>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
You have selected "Date" as the rolling type. So it will separate different logs depending on datePattern:
<datePattern value="yyMMdd_HHmmss'.log'" />
I believe this will make a new log every SECOND. Since this is the smallest value you specified in your log date pattern.
If you just want one log, then disable rolling!
Or if you want a daily log use:
<datePattern value="yyMMdd'.log'" />
I think you will need to look at the how to use the configs for log4net. Current config looks like it is used for rolling file appender by date.
If you are not concerned about date, please follow the guide described in log4net's site: https://logging.apache.org/log4net/release/config-examples.html#fileappender
I am using log4net to perform daily logging.
I realize that log4net doesn't support deleting old files in this fashion.
I am trying to write my own method to accomplish this task, however I am no sure how to read the log4net settings from the web.config file.
I've tried:
var log4NetData = ConfigurationManager.GetSection("log4net");
However I get this as my results:
The type 'System.Configuration.ConfigXmlElement' exists in both 'System.Configuration.dll' and 'System.dll'
How can I read the log4net node from my web.config?
Actually Log4Net can update the same file always (this way, there is no need to delete it and create another one).
I'm using log4Net to log always the same file n times in a hour. My configurations:
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
app.config:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="MyFileAppender" />
</root>
<appender name="MyFileAppender" type="log4net.Appender.FileAppender">
<file value="application.log" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level - %message%newline" />
</layout>
</appender>
</log4net>
I'm getting started with log4net.I'm working on a small console project in which i must implement this framework.
At the beginning i created a small console project to see how it works without any other code.
I managed to make it work properly.
Now i try to migrate all the code in my application and i get this error when i execute the .exe of my console application:
"ERROR failed to find configuration section "log4net" in the application's .config
file.Check your .config file for the <log4net> and <configSections> elements. The
configuration section should look like : <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler.log4net"/>
The code:
public class Program
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
ILog log = log4net.LogManager.GetLogger(typeof(Program));
...
The app.config didn't exist yet so its content is the same as the test project i did:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" />
</configSections>
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender,log4net">
<file value="D:\WEB\SAI\log\nas\log.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
</appender>
<root>
<level value="INFO"/>
<appender-ref ref="FileAppender"/>
</root>
</log4net>
</configuration>
After some searches on internet, i added:
[assembly: log4net.Config.XmlConfigurator()]
to my AssemblyInfo.cs as it was suggested but the result is still the same...
Thanks in advance for your help
ADD
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
in AsseblyInfo.cs
First time playing with Log4Net and I'm running into trouble. I've followed various tutorials but I've been unable to get it to log anything out. Let me show you my code and hopefully you can tell me what I'm doing wrong.
app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="CurrentLog.txt"/>
<staticLogFileName value="true"/>
<appendToFile value="true"/>
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd"/>
<filter type="log4net.Filter.LevelRangeFilter">
<acceptOnMatch value="true" />
<levelMin value="DEBUG" />
<levelMax value="FATAL" />
</filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{dd MMM yyy HH:mm:ss} %level %message. %newline %exception" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
</configuration>
AssemblyInfo.cs
[assembly: log4net.Config.XmlConfigurator(Watch=true)]
Presenter.cs
At the top of the class I have this:
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Then I try to use the log variable later in the class:
bool isDebugEnabled = log.IsDebugEnabled;
log.Debug("Failed to save", e);
Whenever I inspect the isDebugEnabled variable, it is false, as are all of the other isBlahEnabled if I inspect the log variable.
My suspicion is that I have not hooked up my app.config file correctly because this is the first time I have tried to use one. I created by right clicking on the project in solution explorer, adding a new item, choosing Application Configuration File and naming it app.config.
This one works for me:
app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="Main" type="log4net.Appender.RollingFileAppender">
<file value="${USERPROFILE}\My Documents\MyApp\Logs\Main.log" />
<appendToFile value="false" />
<maximumFileSize value="1GB" />
<maxSizeRollBackups value="3" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{ABSOLUTE} %-5level %-18logger %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="Main" />
</root>
</log4net>
</configuration>
Also be sure the build action on app.config is set to None and Copy to output dir is set to "Copy if newer". You can set these settings in the file properties.
Program.cs
public static ILog Log;
static void Main(string[] args)
{
// Setup Logging
log4net.Config.XmlConfigurator.Configure();
Log = LogManager.GetLogger("MyAwesomeApp");
// ...
}
Just to add my 2 cents: I had the same Problem, but I use the above config in separate log4net.config (so I have on all apps the same config), but I simply forgot to set the file property on build 'Copy when newer' (or similar wording, have German Version).
Just to add my 2p in case this helps anyone else searching for a resolution to this problem:
In my case I was using the NServicebus.Logging package in addition to Log4net, and this package contains types with the exact same names as those in Log4net, differing only in the namespace.
Fixing the 'using' statements or fully-qualifying the type names resolved it, but it was very hard to spot the problem.