如何用C#写入日志文件 [英] How to write in log Files in C#

查看:163
本文介绍了如何用C#写入日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在编写代码来用C#创建日志文件。

我发现在下面的实现中遇到了困难


一旦文件大小超过100 MB,就应该创建一个新文件,并且新文件的名称应该附加-1(比如LogFile-1.log)和所有文件日志记录应该在新文件中发生。



我的问题是,如何查找,当前日志文件以及当前日志文件大小是否超过限制,应该创建一个新文件,然后在新文件中进行后续记录。



以下是我的代码



Hi,

I am writing code to create log files in C#.
I am finding difficulties in implementing below

Once the file size exceeds 100 MB, a new file should be created and the name of the new file should be appended with -1 (say LogFile-1.log) and all the logging should happen in the new file.

My problem is that, how do I find out, which is the current log file and if the current log file size exceeds the limit, a new file should be created and subsequent logging should happen in the new file.

below is my code

if (!File.Exists(fileName))
{
    // Create the file.
    fs = File.Create(fileName);
    fs.Close();
}

//Open file
fs = File.Open(fileName, FileMode.Append, FileAccess.Write);
Publish(obj);// this method writes the data into the file



代码示例将有所帮助。

可以某人请帮帮我?

谢谢



问候



代码块添加,忽略HTML ...选项被禁用 - OriginalGriff [/ edit]


Code sample will be helpful.
Can someone please help me?
Thanks

Regards

[edit]Code block added, "Ignore HTML..." option disabled - OriginalGriff[/edit]

推荐答案

这比它需要的更复杂,因为你想保持现有文件并启动一个具有不同名称的新文件。



结果, fileName 你是使用可能不是您要保存的文件的名称,并且您必须假设它不是因为您不知道是否可以传递新名称备份链 - 代码可能是:

This is more complex than it needs to be, because you want to keep the existing file and start a new one with a different name.

As a result, the fileName you are using may not be the name of the file you are saving to, and you have to assume that it isn't because you don't know if you can pass a new name "back up the chain" - the code may be:
Log(@"C:\Logs\LogFile.txt", MyLogMessage);

这意味着每次登录时它都是相同的方法被调用。这意味着每次尝试记录某些内容时,您必须搜索指定目录中与给定文件名匹配的所有文件,并且附加任意数量的-1。然后你可以把你的日志条目添加到最后一个。



例如:

原始文件:LogFile.txt

它填满了,所以你创建了LogFile-1.txt并且必须填写它。

填满,所以你创建了LogFile-1-1.txt并开始填充它。 />
等等。



如果你必须这样做那么你手上有一个小而烦人的工作!

相反,我会这样工作:

文件基本文件,直到它满(100mb)。

用当前日期和时间的前缀重命名基本文件,以YYYYMMDDHHmmss格式。

创建一个新的日志文件,并从中开始工作。



更容易找到文件的顺序进入,如果您知道记录的时间,则更容易找到特定条目。记录条目要容易得多!

Which mean it will be the same each time the Log method is called. This means that every time to try to log something, you must search for all files in the specified directory which match the file name given, and a have any number of "-1"s appended to them. You can then add your log entry to the last one.

For example:
Original File : LogFile.txt
It filled up, so you create LogFile-1.txt and have to fill that.
It fills up, so you create LogFile-1-1.txt and start filling that.
And so on.

If you must it this way then you have a small and annoying job on your hands!
Instead, I would work like this:
File the base file until it is full (100mb).
Rename base file with a prefix for the current date and time, in YYYYMMDDHHmmss format.
Create a new log file, and work from that.

It is easier to find the order the files should go in, and easier to find a specific entry if you know when it was logged. And a whole lot easier to log an entry!


我将如何做到这一点:

How I would do this:
if(!File.Exists(filename)) //No File? Create
{
    fs = File.Create(filename);
    fs.Close();
}
if(File.ReadAllBytes().Lenght >= 100*1024*1024) // (100mB) File to big? Create new
{
    string filenamebase = "myLogFile"; //Insert the base form of the log file, the same as the 1st filename without .log at the end
    if(filename.contains("-")) //Check if older log contained -x
    {
         int lognumber = Int32.Parse(filename.substring(filename.lastIndexOf("-")+1, filename.Length-4); //Get old number, Can cause exception if the last digits aren't numbers
         lognumber++; //Increment lognumber by 1
         filename = filenamebase + "-" + lognumber + ".log"; //Override filename
    }
    else 
    {
         filename = filenamebase + "-1.log"; //Override filename
    }
    fs = File.Create(filename);
    fs.Close();
}





这将检查日志是否存在,并且类中给出了文件名(最好保护文件名,否则你可以使它成为一个字符串函数返回文件名然后在日志附加功能中使用它。但它只是避免它,因为你必须安全早期使用的文件名s omewhere使用此方法。



This will check if the log exists with the filename given in the class (Would be best to safe the filename, else you could make it a string function returning the filename and then use it in the log append function. But it would just avoid it as you got to safe the earlier used filename somewhere with this method.

public string sLogname(string filename)
{
    //Code which alters filename
    return filename;
}



所以我建议以这种形式使用它:


So I suggest to use it in this form:

class Logger {

    string filename;

    public Logger(string basefilename)
    {
        filename = basefilename;
    }

    void Publish(Object obj)
    {
         checkLogFile();
         //Coding of Publish
    }
    
    void checkLogFile()
    {
        //Code of first example
    }
}



请注意,如果不包含编译错误,我会编写所有代码,不检查。


Note that I wrote all code with-out checking if it doesn't contain compile errors.


除了上述答案你也可以阅读这个 [ ^ ]文章
In addition to above answers you can also read this[^] article


这篇关于如何用C#写入日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆