How can .NET TraceListener be configured to log to TEMP folder

◇◆丶佛笑我妖孽 提交于 2019-12-23 18:33:49

问题


How can .NET TraceListener be configured to log to TEMP folder? Is it possible to do this in app.config like:

      <add type="System.Diagnostics.TextWriterTraceListener" 
          initializeData="%Temp%\logfilename.log"/>

.. without making any code changes?

Or can this only be done if you create your listener in code?


回答1:


You'd have to set it in your code.

As you can see in the source code, the constructor immediately assigns to file name with no parsing of the internal structure of the file name.

 public TextWriterTraceListener(string fileName, string name) : base(name) {
            this.fileName = fileName; 
        } 

And then there is some code to deal with the possibility that the file is already locked, but nothing to deal with the possibility that the folder isn't writable (TEMP is usually a writable folder of last resort)

    string fullPath = Path.GetFullPath(fileName);
                    string dirPath = Path.GetDirectoryName(fullPath); 
                    string fileNameOnly = Path.GetFileName(fullPath);
//more code
       fileNameOnly = Guid.NewGuid().ToString() + fileNameOnly;
                        fullPath = Path.Combine(dirPath, fileNameOnly); 


来源:https://stackoverflow.com/questions/33167102/how-can-net-tracelistener-be-configured-to-log-to-temp-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!