Log4net to generate log files dynamically - c#

In my application I use log4net for logs creation. I want to create the log files in the location where the application gets installed.That is , the log files should be generated in c:\App_Instal_path\Logs(folder), if the application is installed under c:\.If it is D:\ then the log files should be under D:\App_Instal_path\Logs(folder). I have done like:
<appender name="ColoredFileAppender" type="log4net.Appender.RollingFileAppender" >
<file type="log4net.Util.PatternString"/>
<file value=***NEEDS TO BE FILLED*** />
Any responses would be really appreciated..

You can put the logfile near your exe file, if you write like this:
<file value="log-file.txt" />
In that case, you put the logfile in folder Logs, near your exe file:
<file value="Logs/log-file.txt" />
In that case, you put the logfile in system TMP folder:
<file value="${TMP}\log-file.txt" />
Look here for more information:
http://logging.apache.org/log4net/release/config-examples.html

Related

Log4Net is not creating logs in bin folder in Asp.Net Core 3.1 API

I am trying to write logs in Asp.NEt Core 3.1 API. but it's not writing to the bin folder. instead, it has created the log file in the Temp folder in project directory.
Microsoft.Extensions.Logging.Log4Net.AspNetCore version 3.1.0
log4net.config
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<file value="Temp\" />
<datePattern value="yyyy-MM-dd.'txt'"/>
<staticLogFileName value="false"/>
<appendToFile value="true"/>
<rollingStyle value="Date"/>
<maxSizeRollBackups value="100"/>
<maximumFileSize value="15MB"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level App %newline %message %newline %newline"/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="RollingLogFileAppender"/>
</root>
</log4net>
Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddLog4Net();
}
This line is setting the folder to Temp: <file value="Temp\" />.
Change it to the full path of the bin folder or to the path of the bin folder relative to your working directory of your application.
For example: .\ or .\bin\
By default Visual Studio will run your project and set the working directory to the project path.
On your project settings, in the Debug section you can manually override the working directory to bin, or you can change Launch mode from Project to Executable and select the executable on your bin folder.
log4net will always use current directory (working directory)to as the root of realitve path defined in config file, so when application was started via VS, it is pointing to project folder, when application was started directly in bin folder, log file would be placed in bin folder.

log4net not logging when the exe is running from startup but works fine when started manually

log4net is not generating the log file nor writing logs into the file when the application is running from the registry start up. But when the application is executed manually, the files are created.
The start up registry key is created in path "[HKEY_LOCAL_USER\Software\Microsoft\Windows\CurrentVersion\Run". When the user logs into the machine the application has to run automatically.
Have a separate log4net.config file for all the log configuration
The log file is created in the user roaming profile.
Things tried:
1. I tried saving in some general path also like (C:\logs\app) still the logs are not created.
2. Run the .exe from command prompt both from user context and administrator privileges, No use.
Log4net Config
<log4net>
<appender name="RollingLogFileAppender"
type="log4net.Appender.RollingFileAppender">
<file value="${APPDATA}\app\app.txt"/>
<appendToFile value="true" />
<rollingStyle value="Date"/>
<rollInterval value="Week"/>
<DatePattern value="'.'yyyy-MM-dd'.log'"/>
<rollSizeKB value="50000"/>
<preserveLogFileNameExtension value="true" />
<countDirection value="1" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="[%date{dd MMM yyyy HH:mm:ss}] [%-5level]
[%-5.70logger] - %message%newline"/>
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
Initialising the config
log4net.Config.XmlConfigurator.Configure(new FileInfo("log4net.config"));
I expect to see a log file at path C:\Users[User]\AppData\Roaming\app\app.txt" but it is not there. Any help in this regard is highly appreciated.
Try with absolute path for your log file and see if it helps. I had the same problem where executing the exe manually logs the data but when run through command prompt, keeps mum.

Nuget Readonly Resources

I'm creating a DTO generator to be shared between projects I have a ttinclude file with some logic in it. In my nuspec I'm including files like so:
<files>
<file src="T4Generators\AutoMapperExtensions.ttinclude" target="content\T4Generators\AutoMapperExtensions.ttinclude"/>
<file src="T4Generators\ConstGenerator.ttinclude" target="content\T4Generators\ConstGenerator.ttinclude"/>
<file src="T4Generators\DTOGenerator.ttinclude" target="content\T4Generators\DTOGenerator.ttinclude"/>
<file src="T4Generators\EnumGenerator.ttinclude" target="content\T4Generators\EnumGenerator.ttinclude"/>
</files>
Is there a way to make these files read-only, since they are shared between projects people have a tendency to make changes to the include instead of going to my source (this is an internal resource).

How to connect to Azure file share from Visial Studio or any other way to LOG my file from Azure

I developed a bidding project AND deployed it on Microsoft Azure.Now I
m trying to log my project. I am using LOG4net and using rollingAppender to log all my required log's to a ".txt" file. As I am using an Azure instead of a my own server, I am unable to give a path for the logging file in the web.config
<log4net>
<appender name="Rollingappender" type="log4net.appender.RollingFileAppender">
<file value="C:\Logs\MyLogfile.txt" />
<file type="log4net.Util.PatternString" value="LOG_%date{yyyy-mm.dd}.txt" />
<appendToFile value="True" />
<rollingStyle value="Size" />
<Maxiumfilesize value="10MB " />
<maxrollbackups value="5" />
<staticLogFileName value ="true" />
<layout type="log4net.layout.patternlayout">
<conversionPattern value="%date{ABSOLUTE} [%logger] %level - %message%newline%exception %username " />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="Rollingappender" />
</root>
</log4net>
above is the code in web.config file,it would work for local machine.
As I'm deploying through Azure and so i published the whole project in azure and user can access my project from azure.Now what path should i give to log my file?
,where can i log them? because "<file value="C:\Logs\MyLogfile.txt" />" this path wont work any more.
I even tried to create a storage in Azure FILESHARE, but unable to connect to it.
For Azure App Service (Web App or formerly known as Websites), you can enable diagnostic logging which will give you the choice to log to Azure Blob storage, Azure File or Local File.
https://azure.microsoft.com/en-us/documentation/articles/web-sites-enable-diagnostic-log/
RE: But I have various kinds of logs...I need a log which stores.txt files and another which stores in a database table.so once I configure diagonistcs lot's application logging to a particular storage ,which is either a blog storage or a table storage I can not configure it to another.I need two kinds of logs in my case.
In this case, i think you will have to implement your own trace listener.
https://msdn.microsoft.com/en-us/library/ff650498.aspx?f=255&MSPPError=-2147217396

How to setup log4net so that it works on a wcf service?

I'm working with a solution on visual studio 2008, .net framework 3.5, windows 7. I've created a log4net library that writes to a txt file and want to use it on several projects on my solution and also on a wcf service that's in the same solution which is running locally from visual studio.
I start the program from a console application on the solution. And the console app calls the other projects and those projects use the log4net. At this level in the workflow the log is writing fine. The problem comes when the wcf service is called. The wcf service uses the log, but log4net doesn't write to the file.
On the console project I have this:
On the AssemblyInfo.cs:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
On the App.config I have the log4net configuration.
On Program.cs, on the Main method I have:
LogManager.GetLogger("Initialise log4net from the current assembly attributes");
On the WCF Service I have this:
The same on the AssemblyInfo.cs as the console project.
Same on Web.config as the App.config on the console project.
On the constructor of the Service1.svc I have:
LogManager.GetLogger("Initialise log4net from the current assembly attributes");
This is how my App.config and Web.Config loos like:
inside the configSections tag:
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
and inside the main configuration tag:
<log4net>
<root>
<level value="DEBUG"/>
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
<file value="C:\test3.txt"/>
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p %c %m%n" />
</layout>
</appender>
</log4net>
How can I solve this?
Do you have an example of the XmlConfigurator so I can configure the logging?
var logpath = HostingEnvironment.MapPath("~/web.config");
var fileInfo = new FileInfo(logpath);
if (fileInfo.Exists == false)
{
throw new InvalidOperationException("Can't locate the web.config file");
}
log4net.Config.XmlConfigurator.ConfigureAndWatch(fileInfo);
Note that only the overload of the ConfigureAndWatch method which takes a FileInfo can watch an app.config or web.config as it reads the .config file directly instead of using System.Configuration (which once it reads the file cannot re-read it).
The documentation explains this here.
Edit by #pyram: because both projects are logging to the same file it was necessary to add this line to the appender config of both projects:
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
Log4Net Configuration in WCF should be as below:
Install Log4net nugget package in your project
This will add log4net package to references, double check.
Add the following line in AssemblyInfo.cs
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.xml", Watch = true)]
Create log4net.xml in application root, and add configurations for logging, as below:
Add log property in service to use it in every method:
private static readonly log4net.ILog _log = log4net.LogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Use _log as follow:
catch (System.Exception ex) _log.Error(ex);

Categories