首页 > 解决方案 > 多个文件到单个文件的符号链接

问题描述

我有一个场景,我想将多个文件的日志重定向到同一个符号链接。
我假设三个文件file1.log file2.log并且file3.log
file1.log

This is file 1

file2.log

This is file 2

file3.log

This is file 3

现在我想创建所有这个文件的符号链接,file.log 这样的内容file.log

This is file 1
This is file 2
This is file 3

这是动态发生的。即如果内容file1.log被修改,那么例如This line append to file1.log应该file1.log显示

This is file 1
This is file 2
This is file 3
This line append to file1.log

有没有这样做的标准方法?我已经在这里停留了很长一段时间。
我正在使用ubuntu 18.04----------------------------- python 3.6.9
EDIT---------------- -------------------
这不是我拥有的所有文件,比如 20 个带有名称的文件,file*.log并且可能有多个文件f1X.log f2X.log需要重定向到f1.logf2.log

标签: pythonubuntuunixloggingsymlink

解决方案


from itertools import chain
from pathlib import Path
from time import sleep

log_path_list = [p for p in Path('.').glob('*.log') if p.name != 'file.log']
log = Path('file.log')

files = []
for log_path in log_path_list:
    files.append(log_path.open())
lines = chain(*map(lambda f: (line for line in f),files))
with log.open('w') as flog:
     for line in lines:
         flog.write(line)
     flog.flush()
     try:
         while True:
            oneline = ""
            for f in files:
                 f.seek(0, 2)
                 oneline = f.readline()
                 if not oneline:
                     continue
                 flog.write(oneline)
            if oneline:
                 flog.flush()
            else:
                 sleep(0.3)
     except Exception as e:
         print(e)
         for f in files:
             f.close()

这不是符号链接,但它会将所有日志文件中的所有内容输出到file.log,然后将任何新行附加到file.log.

只要file.log需要更新,python 进程就应该留在那里。

我不认为这是一个聪明的解决方案,但如果这是你的唯一方法,那么你就有了一个解决方案的开始。


推荐阅读