[英]How can I safely read Log4j logs while another thread is logging at the same time?
If I have multiple threads that use log4j to write to a single log file, and I want another thread to read it back out, is there a way to safely read(line by line) those logs such that I always read a full line? 如果我有多个线程使用log4j写入单个日志文件,并且我希望另一个线程将其读回,是否有办法安全地(逐行)读取那些日志,以便我始终读取整行?
EDIT: Reason for this is I need to upload all logs to a central location and it might be logs that are days old or those that are just being written 编辑:原因是我需要将所有日志上传到中央位置,并且可能是已有几天历史的日志或刚刚被写入的日志
You should use a read write lock. 您应该使用读写锁。
Read locks can be held by multiple users if there is no one writing to the file, but a write lock can only be held by 1 thread at a time no matter what. 如果没有人对文件进行写入,则可以由多个用户持有读取锁,但是无论如何,一次只能由1个线程持有写入锁。
Just make sure that as your writing thread is done writing, it releases the readwritelock to allow the reading threads to read. 只要确保在您的写线程完成写后,它就会释放readwritelock以允许读线程读取。 Likewise, always release the read lock when the reader are done reading so log4j can continue to write
同样,请在读取器完成读取后始终释放读取锁定,以便log4j可以继续写入
Check out 查看
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReadWriteLock.html http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReadWriteLock.html
However, coming to think of it, what is your purpose for this? 但是,想到这一点,您的目的是什么? If you simply want to monitor your logs, you should use a different solution rather than having a monitor thread within the same application.
如果只想监视日志,则应使用其他解决方案,而不要在同一应用程序中使用监视线程。 Seems to not make sense.
似乎没有道理。 If the data is available within the application / service, why pass it off to a file and read it right back in?
如果数据在应用程序/服务中可用,为什么将其传递给文件并立即读回?
It is going to be a pain if you need to implement what you are doing, especially you have to deal with file rolling. 如果您需要实现自己正在做的事情,那将会很痛苦,尤其是必须处理文件滚动时。
For your specific requirement, there are better choices: 根据您的特定要求,有更好的选择:
If the location you are going to be backed up can be directly written (ie mounted in your file system), it is better to simply set your file rolling to write to that backup directory; 如果您要备份的位置可以直接写入(即挂载在文件系统中),则最好简单地将文件滚动设置为写入该备份目录。 or
要么
Make use of log management tools like Splunk to monitor and manage your log files (so that you don't even need to copy to that backup directory); 利用Splunk之类的日志管理工具来监视和管理您的日志文件(这样,您甚至无需复制到该备份目录); or
要么
Even you need to do the backup all by yourself, you don't need to (and have no reason to) do it in a separate thread. 即使您需要自己全部进行备份,也不需要(也没有理由)在单独的线程中进行备份。 Trying to write a shell script monitoring your log directory, and make use of tools like rsync or write similar logic by yourself, to do the upload only for files that are not matching in local and remote location.
尝试编写一个监视您的日志目录的Shell脚本,并使用rsync之类的工具或自己编写类似的逻辑,以仅对本地和远程位置不匹配的文件进行上载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.