简单的日志文件操作类 (C#)

类名称: log;

类方法(公有):

1)  log (String)    构造函数,传入完整文件名。

2)bool writeln_log (String)   写入一行日志字符串。

3) static void del_log_file (String)   删除指定文件。

4) bool close_file ()   关闭文件

5)   (属性)  String filepath (读写)     获取或设置文件流打开的完整文件名,若设置则动态改变文件流,使之导向到新的文件。


使用方法:

using lib_ez;


log _log = new log (@"C:\testfile.dat");
_log.writeln_log ("add the first log string...");
_log.writeln_log ("add another log string...");

// redirect stream
_log.filepath = @"C:\another.dat";
_log.writeln_log ("add the first log string to another.dat file...");

// close
_log.close ();

类源代码:

文件: log.cs

/*
	author : ez
	date : 2015/4/13
	describe : a class to support writing log string into logfile
*/
namespace lib_ez {

    using System;
    using System.Collections;
    using System.Collections.Generic;

    using System.IO;

    public class log {

		// support dynamically file path changing
        public String filepath {
            get { return this._logfile; }
            set {
                if (this._writer != null && close_file ())
                    this._writer = new StreamWriter (this._logfile = value, true); // support appending writing
                else
                    open_file (this._logfile = value);
            }
        }

        public log (String __log_file) {
            this.open_file (this._logfile = __log_file);
        }

        public bool writeln_log (String __str) {
            if (this._writer == null && !this.open_file (this._logfile))
                return false;
            this._writer.WriteLine (__str);
            this._writer.Flush ();
            return true;
            /*
            if (this._fs == null && ! this.open_file (this._logfile))
                return false; // error in close file
            writer = new StreamWriter (this._fs);
            writer.WriteLine (__str);
            return true;
            */
        }

        public static void del_log_file (String __file) {
            if (File.Exists (__file))
                File.Delete (__file);
        }

        private bool open_file (String __log_file) {
            try {
                this._writer = new StreamWriter (__log_file, true);
                return true;
            }
            catch (Exception ex) {
				// show exception message to Console
                Console.WriteLine ("lib_ez.log.open_file [" + DateTime.Now.ToString () + "] : " + ex.Message);
                return false;
            }
        }

		// always return true
        public bool close_file () {
            this._writer.Dispose ();
            return true;
        }

        private StreamWriter _writer;
        private String _logfile;
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值