首页 > 解决方案 > 使用 Form 应用程序更改记录器的路径并使用 C# 将其实现为服务

问题描述

我正在开发一个 File Watcher 服务,其中也有一个表单应用程序(同一解决方案中有 2 个不同的项目)。因此,我得到了使用 Forms 应用程序保存日志的路径。然后我把它放在我的app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="location" value="C:\Users\user\Documents" />
        <add key="logLocation" value="C:\Users\user\Documents" /> <!-- this is where it changes save it-->
    </appSettings>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
</configuration>

我有一个Variables定义变量的类。

using System.Configuration;

namespace FileWatchingService
{
    public static class Variables
    {
        public static string FilePath { get; set; } = ConfigurationManager.AppSettings.Get("location");
        public static string LogPath { get; set; } = ConfigurationManager.AppSettings.Get("logLocation");
    }
}

然后我试着把我的 LogPath 放在这里:

using System;
using System.IO;

namespace FileWatchingService
{
    public static class Logger
    {
        public static void Log(string message)
        {
            try
            {
                string _message = String.Format("{0} {1}", message, Environment.NewLine);
                //File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "logFile.log", _message);
                File.AppendAllText(Variables.LogPath + "logFile.log", _message);
            }
            catch (Exception ex)
            {
                //Implement logging on next version
            }
        }
    }
}

问题是我的方法行不通。我可以做些什么来更改我的日志文件路径?

标签: c#winformsservice

解决方案


仅查看代码,您似乎在LogPath\的末尾缺少 a 。您还可以执行或仅定义 LogPath 本身,例如:File.AppendAllText(Variables.LogPath + "\logFile.log", _message);

 <appSettings>
    <add key="location" value="C:\Users\user\Documents" />
    <add key="logLocation" value="C:\Users\user\Documents\log.txt" /> <!-- the file itself -->
  </appSettings>

不过,我建议只使用一个库进行日志记录,而不是自己开发。使用NLogSerilog


推荐阅读