using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows.Forms; namespace app.Lib
{
public enum Level
{
Debug,
Exception,
Info,
Warn,
} public enum Priority
{
None,
High,
Medium,
Low,
}
public class Logger
{
private static StreamWriter _writer;
//private static string _format = "{1}: {2}. Priority: {3}. Timestamp:{0:u}";
private static string _format = "{0:u}:{1:D3} {2}: {3}";
private static StreamWriter Writer
{
get
{
if (_writer == null)
{
string path = Application.StartupPath + "//Log//" + DateTime.Now.ToString("yyyy") + "//" +
DateTime.Now.ToString("yyyyMM") + "//" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log";
string filepath = Application.StartupPath + "//Log//" + "//bmp//"; string dir = Path.GetDirectoryName(path);
string filedir = Path.GetDirectoryName(filepath); if (filedir != null && !Directory.Exists(filedir))
{
Directory.CreateDirectory(filedir);
} if (dir != null && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
_writer = new StreamWriter(path, true, Encoding.Default);
_writer.AutoFlush = true;
}
return _writer;
}
} public static string GetFileDirName()
{
return Application.StartupPath + "//Log" + "//bmp//";
} public static void Log(string message, Level level)
{
string messageToLog = String.Format(CultureInfo.InvariantCulture, _format, DateTime.Now, DateTime.Now.Millisecond,
level.ToString().ToUpper(CultureInfo.InvariantCulture), message); Writer.WriteLine(messageToLog);
} public static bool EnableLog;
}
}

很多时候需要为我们应用程序添加日子文件,方便问题定位

代码转载而来,非原创

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection; namespace CommonLib
{
/// <summary>
/// 日志类型
/// </summary>
public enum LogType
{
All,
Information,
Debug,
Success,
Failure,
Warning,
Error
} public class Logger
{ #region Instance
private static object logLock; private static Logger _instance; private static string logFileName;
private Logger() { } /// <summary>
/// Logger instance
/// </summary>
public static Logger Instance
{
get
{
if (_instance == null)
{
_instance = new Logger();
logLock = new object();
//logFileName = Guid.NewGuid() + ".log";
logFileName = DateTime.Now.Hour.ToString("") + DateTime.Now.Minute.ToString("") +DateTime.Now.Second.ToString("") + ".log";
}
return _instance;
}
}
#endregion /// <summary>
/// Write log to log file
/// </summary>
/// <param name="logContent">Log content</param>
/// <param name="logType">Log type</param>
public void WriteLog(string logContent, LogType logType = LogType.Information, string fileName = null)
{
try
{
string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
basePath = Directory.GetCurrentDirectory(); //@"C:\APILogs";
if (!Directory.Exists(basePath + "\\Log"))
{
Directory.CreateDirectory(basePath + "\\Log");
} string dataString = DateTime.Now.ToString("yyyy-MM-dd");
if (!Directory.Exists(basePath + "\\Log\\" + dataString))
{
Directory.CreateDirectory(basePath + "\\Log\\" + dataString);
} string[] logText = new string[] { DateTime.Now.ToString("hh:mm:ss") + ": " + logType.ToString() + ": " + logContent };
if (!string.IsNullOrEmpty(fileName))
{
fileName = fileName + "_" + logFileName;
}
else
{
fileName = logFileName;
//fileName = DateTime.Now.ToString("hh:mm:ss");
} lock (logLock)
{
File.AppendAllLines(basePath + "\\Log\\" + dataString + "\\" + fileName, logText);
}
}
catch (Exception) { }
} /// <summary>
/// Write exception to log file
/// </summary>
/// <param name="exception">Exception</param>
public void WriteException(Exception exception, string specialText = null)
{
if (exception != null)
{
Type exceptionType = exception.GetType();
string text = string.Empty;
if (!string.IsNullOrEmpty(specialText))
{
text = text + specialText + Environment.NewLine;
}
text = "Exception: " + exceptionType.Name + Environment.NewLine;
text += " " + "Message: " + exception.Message + Environment.NewLine;
text += " " + "Source: " + exception.Source + Environment.NewLine;
text += " " + "StackTrace: " + exception.StackTrace + Environment.NewLine;
WriteLog(text, LogType.Error);
}
} }
}
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection; namespace CommonLib
{
/// <summary>
/// 日志类型
/// </summary>
public enum LogType
{
All,
Information,
Debug,
Success,
Failure,
Warning,
Error
} public class Logger
{ #region Instance
private static object logLock; private static Logger _instance; private static string logFileName;
private Logger() { } /// <summary>
/// Logger instance
/// </summary>
public static Logger Instance
{
get
{
if (_instance == null)
{
_instance = new Logger();
logLock = new object();
//logFileName = Guid.NewGuid() + ".log";
logFileName = DateTime.Now.Hour.ToString("") + DateTime.Now.Minute.ToString("") +DateTime.Now.Second.ToString("") + ".log";
}
return _instance;
}
}
#endregion /// <summary>
/// Write log to log file
/// </summary>
/// <param name="logContent">Log content</param>
/// <param name="logType">Log type</param>
public void WriteLog(string logContent, LogType logType = LogType.Information, string fileName = null)
{
try
{
string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
basePath = Directory.GetCurrentDirectory(); //@"C:\APILogs";
if (!Directory.Exists(basePath + "\\Log"))
{
Directory.CreateDirectory(basePath + "\\Log");
} string dataString = DateTime.Now.ToString("yyyy-MM-dd");
if (!Directory.Exists(basePath + "\\Log\\" + dataString))
{
Directory.CreateDirectory(basePath + "\\Log\\" + dataString);
} string[] logText = new string[] { DateTime.Now.ToString("hh:mm:ss") + ": " + logType.ToString() + ": " + logContent };
if (!string.IsNullOrEmpty(fileName))
{
fileName = fileName + "_" + logFileName;
}
else
{
fileName = logFileName;
//fileName = DateTime.Now.ToString("hh:mm:ss");
} lock (logLock)
{
File.AppendAllLines(basePath + "\\Log\\" + dataString + "\\" + fileName, logText);
}
}
catch (Exception) { }
} /// <summary>
/// Write exception to log file
/// </summary>
/// <param name="exception">Exception</param>
public void WriteException(Exception exception, string specialText = null)
{
if (exception != null)
{
Type exceptionType = exception.GetType();
string text = string.Empty;
if (!string.IsNullOrEmpty(specialText))
{
text = text + specialText + Environment.NewLine;
}
text = "Exception: " + exceptionType.Name + Environment.NewLine;
text += " " + "Message: " + exception.Message + Environment.NewLine;
text += " " + "Source: " + exception.Source + Environment.NewLine;
text += " " + "StackTrace: " + exception.StackTrace + Environment.NewLine;
WriteLog(text, LogType.Error);
}
} }
}

为App添加Log日志文件的更多相关文章

  1. 使用触发器实现记录oracle用户登录失败信息到alert.log日志文件

    前面我们说了用oracle自带的审计功能可以实现记录用户登录失败日志到数据表中(链接:http://www.54ok.cn/6778.html).今天我们来分享一下如何把用户登录失败信息记录到aler ...

  2. log4j.properties配置与将异常输出到Log日志文件实例

    将异常输出到 log日志文件 实际项目中的使用: <dependencies> <dependency> <groupId>org.slf4j</groupI ...

  3. Linux系统的LOG日志文件及入侵后日志的清除

    UNIX网管员主要是靠系统的LOG,来获得入侵的痕迹.当然也有第三方工具记录入侵系统的 痕迹,UNIX系统存放LOG文件,普通位置如下: /usr/adm - 早期版本的UNIX/var/adm -  ...

  4. Android APP测试的日志文件抓取

         1    log文件分类简介 实时打印的主要有:logcat main,logcat radio,logcat events,tcpdump,还有高通平台的还会有QXDM日志 状态信息的有: ...

  5. Android中对Log日志文件的分析[转]

    一,Bug出现了, 需要“干掉”它 bug一听挺吓人的,但是只要你懂了,android里的bug是很好解决的,因为android里提供了LOG机制,具体的底层代码,以后在来分析,只要你会看bug, a ...

  6. C#中添加log4net(日志文件)

    1.先下载引用“log4net” 2.然后再App.config配置 3.添加一个LogHandler类 4.在Assemblyinfo类中添加配置的读取文件 5.运用日志文件 6.显示结果

  7. 关于pptpd log日志文件的配置

    如何开启pptpd默认日志记录功能. 修改/etc/ppp/options.pptpd中的nologfd,默认没有开,把nologfd注释掉,然后添加 logfile /var/log/pptpd.l ...

  8. 怎样在idea添加log日志 以及log4j2配置文件解读

    网上找了很多篇文章,就数这篇比较全,从下载到配置都有讲到,解决从0开始接触java日志文件添加的各位同学.参考文章:https://www.cnblogs.com/hong-fithing/p/769 ...

  9. 解决Linux下Tomcat日志目录下的catalina.log日志文件过大的问题

    本文摘自:(http://blog.csdn.net/stevencn76/article/details/6246162) 分类: Java技术专区2011-03-13 12:25 5017人阅读  ...

随机推荐

  1. Promise来控制JavaScript的异步执行

    一般来说,js.html都是按照从上至下这种方式来进行执行的.这就造成了,基本上所有的执行过程都是在一个线程中进行. 我们都知道,ajax的使用大大的提高了前后台的沟通效率,那么有没有什么方式,让js ...

  2. .Net Framework项目引用.NetStandard标准库出现版本冲突解决办法

    今天在工作中出现一个引用问题,害我找问题找了很久.起因是在一个Winform项目下需要引用一个.NetStandard标准库,标准库引用了System.ComponentModel.Annotatio ...

  3. DSAPI 简单WebAPI实现

    使用DSAPI实现一个简单的WebAPI功能,以便各客户端访问.支持身份验证,支持基础防护. 新建项目(以下演示控制台示例),引用DSAPI.dll. 复制粘贴以下代码: Module Module1 ...

  4. .net core中使用autofac进行IOC

    .net Core中自带DI是非常简单轻量化的,但是如果批量注册就得扩展,下面使用反射进行批量注册的 public void AddAssembly(IServiceCollection servic ...

  5. 简单多播委托Demo

    namespace ConsoleApp4 { class Program { static void Main(string[] args) { Mum mum = new Mum(); Dad d ...

  6. JFreeChart画图+jsp页面显示实现统计图

    1 开发环境: 1.eclipse(可替换) 2.jfreechart-1.0.19 2 说明: (1) source目录:为 jfreechart的源码目录:不会的主要看这里.因为他的文档是收费的. ...

  7. Flutter项目之app升级方案

    题接上篇的文章的项目,还是那个空货管理app.本篇文章用于讲解基于Flutter的app项目的升级方案. 在我接触Flutter之前,做过一个比较失败的基于DCloud的HTML5+技术的app,做过 ...

  8. ext组件中的查询

    组件中的查询依赖于组件树,往上可追溯父组件,往下可查找子组件. 组件中的查询主要包括8个方法:up.down.query.child.nextNode.nextSibiling.previoutNod ...

  9. SQL 获取时间段内日期列表

    declare @start date,@end date; set @start='2010-01-01'; set @end='2010-02-01'; --获取时间段内日期列表 select [ ...

  10. spark2.4 分布式安装

    一.Spark2.0的新特性Spark让我们引以为豪的一点就是所创建的API简单.直观.便于使用,Spark 2.0延续了这一传统,并在两个方面凸显了优势: 1.标准的SQL支持: 2.数据框(Dat ...