FileLogController.cs 2.18 KB
using Hh.Mes.POJO.ViewModel;
using Hh.Mes.Service.SystemAuth;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Linq;

namespace WebMvc.Areas.Planned.Controllers
{
    /// <summary>
    /// 日志文件
    /// </summary>
    [Area("Planned")]
    public class FileLogController : BaseController
    {
        private readonly DirectoryInfo _directory;
        public FileLogController(IAuth authUtil) : base(authUtil)
        {
            _directory = new DirectoryInfo($"{Directory.GetCurrentDirectory()}//Logs");
        }

        public IActionResult Index()
        {
            var vm = _directory.GetDirectories().Select(x => new FileLogVM
            {
                DirectoryName = x.Name,
                FileNames = new DirectoryInfo(x.FullName).GetFiles().Select(f => new FileItems
                {
                    FileName = f.Name,
                    FileSize = $"{f.Length / 1024:N1}Kb"
                }).OrderByDescending(f => f.FileName).ToList(),
            }).OrderByDescending(x => x.DirectoryName).Take(3).ToList();
            return View(vm);
        }

        /// <summary>
        /// 获取日志文件文本
        /// </summary>
        /// <param name="directoryName">目录</param>
        /// <param name="fileLogName">文件名称</param>
        /// <returns></returns>
        public IActionResult GetFileText(string directoryName, string fileLogName)
        {
            try
            {
                var logFilePath = $"{Directory.GetCurrentDirectory()}//Logs//{directoryName}//{fileLogName}";
                if (!System.IO.File.Exists(logFilePath))
                {
                    return Content($"文件不存在!");
                }
                FileStream fs = new FileStream(logFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
                var log = sr.ReadToEnd();
                sr.Close();
                fs.Close();
                return Content(log);
            }
            catch (Exception ex)
            {
                return Content($"日志读取异常:{ex.Message}");
            }
        }
    }
}