var appender = (log4net.Appender.FileAppender)LogManager.GetRepository().GetAppenders()[0];
logger.Info(appender.File);
appender.File = string.Empty;
appender.File = newfileName;
appender.ActivateOptions();
I am changing this at runtime , it runs when a new month begins , it was working fine but for this month it did create a new file but still logging to September file
Related
I'm configuring NLog programmatically with this FileTarget:
var target = new FileTarget(TargetName)
{
FileName = Path.Combine(LogDir, "${level}.log"),
CreateDirs = true,
ArchiveFileName = Path.Combine(LogDir, "{#}.${level}.zip"),
ArchiveNumbering = ArchiveNumberingMode.Date,
ArchiveDateFormat = "yyyy-MM-dd",
ArchiveEvery = FileArchivePeriod.Day,
MaxArchiveFiles = MaxArchiveFiles,
OpenFileCacheSize = 5,
KeepFileOpen = true,
CleanupFileName = false,
Layout = NLogLayouts.BasicLayout(),
EnableArchiveFileCompression = true,
Encoding = Encoding.UTF8
};
Everythings works as it should be: I have separate log file for each log level.
When a new day starts (22.09.2020) AND some message is written to (e.g., INFO) log, archive is created. Its name is 2020-09-21.Info.zip
At the same moment, my program has no new messages to DEBUG level, and no archive is created before such a message is generated. The problem is that DEBUG level message can be written only in 2-3-or more days, but I want the Debug.log file to be archived at the moment day changed - not when a new message comes.
How can I configure NLog to achieve this?
Is there a way to get the full filename from the Log Class?
The logger creates a file with a format like C:\MyPath\log-20160631.txt
I can not access the source filename which i used for the init of the logger.
Edit:
Here is the init of the logger:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.LiterateConsole()
.WriteTo.RollingFile(#"C:\MyPath\log.txt")
.CreateLogger();
In every location in the code i can use e.g. Log.Information() but how i get the Sink information? I want to get the filename which i passed to rolling file sink.
My current workaround is to generate the real file manually (crazy ugly code):
public string LogFilename
{
get
{
string path = Path.GetDirectoryName(LogFilenameTemplate);
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(LogFilenameTemplate);
string extension = Path.GetExtension(LogFilenameTemplate);
string date = DateTime.Now.ToString("yyyyMMdd");
string fullFilename = Path.Combine(path, filenameWithoutExtension + "-" + date + extension);
return fullFilename;
}
}
Format i got from GitHub Repo.
No, there's no way to retrieve the filename from Serilog. Your best available option is to use the System.IO classes to list files in the directory, and then open the one with the most recent modification date.
I am trying to deploy my project having power point slide in solution exlorer. however after I build these it gives me an error as it does not find this ##.ppt file in bin debug. I used build action as content and copy to output directory as copy always but seems of no help. is there any other option for this
Below is my code where I am trying to copy shapes from ppt saved in solution explorer to current ppt now after i deploy since this ppt doesnt add with deployed files it cannot find ppt so it doesnt add shapes.
PowerPoint.Application ppApp = Globals.ThisAddIn.Application;
String programfilesPath = AppDomain.CurrentDomain.BaseDirectory;
//var filesPath = Directory.GetParent(Directory.GetParent(Directory.GetParent(programfilesPath).ToString()).ToString());
String fullPath = programfilesPath;
string pptname = "Moons.ppt";
String themePresentationPath = fullPath + pptname;
// PowerPoint.Application ppapp2 =
var temporaryPresentation = ppApp.Presentations.Open(themePresentationPath, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoTrue);
PowerPoint.SlideRange ppslr = ppApp.ActiveWindow.Selection.SlideRange;
int countlargest = ppslr.Shapes.Count;
string shapecount = harveyballs.SelectedItem.Label.ToString();
int count = Convert.ToInt32(shapecount);
ppslr.Shapes.SelectAll();
PowerPoint.ShapeRange ppShR = ppApp.ActiveWindow.Selection.ShapeRange;
ppShR[count + 1].Copy();
temporaryPresentation.Close();
PowerPoint.SlideRange ppslr2 = ppApp.ActiveWindow.Selection.SlideRange;
ppslr2.Shapes.Paste();
it does not find this ##.ppt file in bin debug
The debug folder is used as an output when current configuration is set to Debug. Are you sure that you have the Debug configuration set in Visual Studio?
My program saves user's input to a txt file on it's current location
TextWriter ts = new StreamWriter("url.txt");
ts.WriteLine(textBox2.Text.ToString());
ts.Close();
It reads that when application starts
if (File.Exists("url.txt")) {
TextReader tr = new StreamReader("url.txt");
readUrl = tr.ReadLine().ToString();
textBox2.Text = readUrl;
tr.Close();
}
I add this program to Windows startup with these code
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true)) {
key.SetValue("House Party Protocol", "\"" + Application.ExecutablePath + "\"");
}
I published it with ClickOnce and installed it to my computer. It starts at windows startup bu doesn't read txt file. When I open it manually it works. I think ClickOnce installation path and windows startup path are different. How should I change my startup code to avoid this
You could try to use a specific directory. For example, you could save the url.txt file to LocalApplicationData (the directory for application-specific data that is used by the current, non-roaming user).
static void Main(string[] args)
{
string inputText = string.Empty;
//string directory = Environment.CurrentDirectory;
string directory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string path = Path.Combine(directory, "url.txt");
if (File.Exists(path))
{
TextReader tr = new StreamReader(path);
string readUrl = tr.ReadLine().ToString();
inputText = readUrl;
tr.Close();
}
string text = "abc";
TextWriter ts = new StreamWriter(path);
ts.WriteLine(text);
ts.Close();
}
If you really want to use the directory where the application is running then you could try to use Environment.CurrentDirectory (commented-out in the sample code above). This might give you the same error you had before (when using relative path) but it might help you troubleshoot the issue by showing what directory it's trying to use.
Here's a list of other special folders:
Environment.SpecialFolder
I am attempting to programmatically create a rolling file appender in C#. I'm using Visual Studios 2008. I am using log4net version 1.2.0.30714.
My main issue is that my rolling file appender is acting like a file appender. The log file will not roll based upon any size or date criteria I give it. Below is my configuration and I would appreciate any insight or suggestions. Below the code is some of the ideas I have tried.
string path = "Logs\";
string filename = "test.log";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
log4net.Layout.PatternLayout patternLayout = new log4net.Layout.PatternLayout("[%d] %l %n - %m %n%n");
patternLayout.ActivateOptions();
RollingFileAppender appender = new RollingFileAppender();
appender.Threshold = Level.ALL;
appender.StaticLogFileName = false;
appender.CountDirection = 0; // Makes the logs count 1, 2, 3
appender.RollingStyle = RollingFileAppender.RollingMode.Size;
appender.MaximumFileSize = "1KB";
appender.MaxFileSize = 1 * 1024; // 1 KB
appender.MaxSizeRollBackups = 5;
appender.DatePattern = "yy.MM.dd.hh.mm.ss";
appender.Layout = patternLayout;
appender.Name = "QTracImportHelper";
appender.ImmediateFlush = true;
appender.File = filename;
appender.Writer = new StreamWriter(path + filename, true);
appender.ActivateOptions();
Hierarchy hierarchy = (Hierarchy)LogManager.GetLoggerRepository();
hierarchy.Root.AddAppender(appender);
hierarchy.Configured = true;
I've noticed that removing the StreamWriter leads to no file being created at all but no exceptions. Removing the file name causes an exception from within log4net. I have tried using both MaxFileSize and MaximumFileSize to no avail as well as changing the rolling stile to Date and Composite. Additionally if the writer stream is malformed it will create the same exception as not including the File property ({"Value cannot be null.\r\nParameter name: fileName"}{System.ArgumentNullException}).
I think this may be due to you supplying the "Writer" parameter directly before the ActivateOptions() call. The writer should be opened by the RollingLogFileAppender not externally. It's only exposed because of the inheritance of the class from TextWriterAppender.
//Don't do this:
//appender.Writer = new StreamWriter(path + filename, true);
//Do fully-qualify the file name:
appender.File = Path.Combine(path, filename);