I have Developed a console application (using C# and oracle) which will read some data from the Database generate a Excel sheet and send the mail to respective Address. In my application I generate a log file and put log in every steps. When my application start running it is creating the Log file and start writing the Log. And my Log file Name is Like:
logFileName = "XYZ"+ "_" + System.DateTime.Today.Date.Day.ToString() + "." + System.DateTime.Today.Date.Month.ToString() + "." + System.DateTime.Today.Date.Year.ToString() + "" + System.DateTime.Now.Hour.ToString()+ ".txt";
This file is generate onetime in a hour and every Execution it is just override the Data. But now I want to generate separate log file for Each Execution of program. If I am trying to add in file name (min,sec) and start writing log file every sec it is generating a new log file in middle of program execution. So I want to Write Total log in End of the program execution or any error encounter to terminate the program. So where should i store the initial log data and finally i need to write it.
I know there are some relevant post but i did not find the relevant to my concern. Please help me out to find the solution.
You can do logging by hand, but I would recommend a logging library like NLOG, which supports your scenario out of the box and is well tested.
http://nlog-project.org/
Add the hour to the end of the file name. That will create the new file.
You can also try File.Create:
Creating an empty file in C#
using (File.Create(filename)) ;
EDIT: You can also just use a stringbuilder to build up the log data, then write to a file at the end.
I would use logging tool like log4net and do the configuration to create log file on each execution
check log4net one file per run and Log4Net basics with a Console Application (c#)
Related
Is there a way to restart the log files using the configured parameters in the config file as if the application was relaunching?
I have file appenders that put the date in the file name, and on certain events I want to close that log and start a new one with the current date/time.
It looks like there is a reset function in the appender class that should do the job, but it is inaccessable.
If found a post that manually sets a new filename and calls the ActivateOptions() function to create a new file, but I don't want to manually set the file name. I want it autogenerated with the pattern that is in the config file.
Any ideas would be appreciated!
Thanks,
John Vickers
So I have a problem in my ASP.NET MVC application, it doesn't want to save the xml file after I publish it. I have a form which I post to a controller using ajax, and then I use that data to create an xml file which i then want to save.
I use the following code to generate my xml file and save it:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(rawXml);
StreamWriter path = new StreamWriter(Server.MapPath("/"+ fileName + ".xml"));
xmlDoc.Save(path);
If I run my application in debug It writes the file to ~/MySolution/MyProject/MyFile, no problem.
So when I publish the app to the IIS 7 server on my computer and load the app through localhost/MyApp, I expect it to write the file to C:\inetpub\wwwroot\MyApp\MyFile but it doesn't.
I have enabled permissions to the folder inetpub and all the subsequent folders for NETWORK SERVICE. But the AJAX post keeps returning in Error and the file doesn't appear in the folder, so I assume it's not allowing to write the file to the specified path, or the path is incorrect, ether way I don't know how to check what's gone wrong.
How do I make the published app write the xml file to the C:\inetpub\wwwroot\MyApp\MyFile path?
First of all it's not recommended to write any files in the root folder as writing to root folder cause appdomain to recycle after certain number of writes (default is 15) causing session loss. See more details here.
I would suggest you to add a path of your server to web.config and then fetch it in your code.Use something like below in the appsettings section of web.config
<add key="filePath" value="C:\inetpub\wwwroot\MyApp" />
Regarding the permissions please add Users group to your folder and give that group full permission (read/write).
To further find out which specific user (as there are too many use cases) is used by w3wp you can use process monitor as explained below
Capture Process Monitor log while reproducing issue
Filter on Access Denied
No Access Denied, so filter on w3wp.exe
Look for access to 401-3.htm
Review entries before the 401-3.htm to determine what file was accessed last
Check permissions based on successful QuerySecurityFile operation for last file accessed (in this case was asp.dll)
I want to delete my Nlog logfile between each application run only if it was emailed to me successfully otherwise it should keep adding to the logfile. I am using Outlook to email the file. I don't want to use Smtp since some networks block port 25 and then it does not get emailed to me.
The problem is when I try to delete the logfile with File.Delete(logfile) is says that the the file is in use by aonther process. How do I unlock or close the file in order for me to email it using Outlook (and then re-open it fo further logging)?
I was thinking of making a copy of the logfile and emailing that, but I'm not sure if its the best way to do it.
Thx for any ideas.
It's not Outlook which prevents the deletion of the file - your application is still running and logging to that file is still active, hence it is the Nlog part of your application which prevents the deletion.
Tell nlog to use a different log file, or not to log at all (you may resume logging later on).
By default nlog doesn't keep files open (file target, keepFileOpen). So either you try to delete file when your application is writing data, or outlook still using the file.
First, you may want to send it via outlook a copy of the log file. So you'd be sure that original file is not locked by an external process.
Second, you'll be able to reconfigure current file target to write to another file (log(n+1).txt or something. There are some hints about programmatic configuration at Add, enable and disable NLog loggers programmatically). So you'll be sure that application isn't logging to the file.
Then you'll be able to remove it, I think.
Option 1 :
if(chkLogger.Checked){
NLog.Config.SimpleConfigurator.ConfigureForFileLogging("Logfile.log",NLog.LogLevel.Trace);
}
else
{
NLog.Config.SimpleConfigurator.ConfigureForFileLogging("Logfile.log", NLog.LogLevel.Off);
}
Option 2 : LogManager.DisableLogging() and LogManager.EnableLogging()
from website Stopping-Starting-NLog-on-runtime
I am developing c# application, which is running as a windows service.
What ever transactions we are doing in the application i am writing it into log file.
A log directory is added in app.config file as below.
<add key ="LogDir" value="log" />
<add key ="LogLevel" value="2" />
And in the c# code the above one is accessing as below.
int logLevel = Convert.ToInt32(ConfigurationManager.AppSettings["logLevel"]);
if (logLevel > 0)
{
logger = new Logger();
logger.TraceLevel = logLevel - 1;
logger.logDir = ConfigurationManager.AppSettings["logDir"];
logger.logFileBaseName = "touchserver";
}
And then when any process is happening i am writing the data to the log as below.
TouchServer.Log(Logger.MessageType.Trace, 1, "Item successfully deleted");
And when i run my application in debug mode (i mean as console application) the log file will be created in the application's debug folder and the data will write into the log file.
But my problem is that when i install my application as service the log file is not getting created in the debug folder, and i am unable to see the actions performed , in case if anything went wrong.
Please help me to find a solution in this.
And i am installing service using Installutil command.
Thanks in advance
sangita
While you could get into why this is not working and fix the solution, overall there is no need to implement a logging component.
There are excellent free libraries available that do this very well. log4net is very popular. It is easy to use, feature rich and efficient. Take a look at it.
But my problem is that when i install my application as service the log file is not getting created in the debug folder, and i am unable to see the actions performed , in case if anything went wrong.
Check out what are the result of the IO operations by using Process Monitor. I suspect you'll find the identity being used to run the service process does not have write permissions where it is trying to write the log file.
But the better option is to use an existing logging library as Hemal suggests.
I have a service that controls an RS-232 device and logs actions to a file. I am to write another service which will read the log file line by line and run some queries on a database then delete all the logs.
My concern is about read and write conflicts on the file. For example, the logger service open the file to append a new line at the same time the replicator service opens the file and write "" so truncate its content.
Any suggestions to clarify my situation?
How about modifying the "read" service to rename the file first (putting a "_" in front of it is what I usually do). And then it can delete it when done. The write service should create the log file if it does not exist. This way you should have zero data loss.
If your are not tied to use a file, the use case would suggest a message queue for handing over your log messages.