代码改变世界

一个简单日志封装

2011-12-29 23:28  j.cheen  阅读(440)  评论(0编辑  收藏  举报

似乎也没有什么好说明的,图个简单易用 :)

直接上代码,声明:

View Code
 1 #ifndef log_warper_h__
2 #define log_warper_h__
3
4 #pragma once
5 #include <string>
6 #include <sstream>
7 #include <iomanip>
8
9 namespace loging
10 {
11 class loger;
12
13 enum loging_level{
14 ll_debug,
15 ll_info,
16 ll_warning,
17 ll_error,
18 ll_fatal_err,
19 ll_end_palce_
20 };
21 class log_warper
22 {
23 public:
24 log_warper();
25 explicit log_warper(loging_level log_lvl);
26 log_warper(loging_level log_lvl,const std::string& source_file,const std::string& func_name,int line_number,int error_code);
27 log_warper(loging_level log_lvl,const std::string& source_file,const std::string& func_name,int line_number);
28 log_warper& reset(loging_level log_lvl,const std::string& source_file="",const std::string& func_name="",int line_number=-1);
29 std::ostream& stream();
30 void finish(bool abort=false);
31 loger& get_impl();
32 ~log_warper(void);
33 private:
34 log_warper(const log_warper&);
35 log_warper& operator=(const log_warper&);
36 private:
37 loger* impl_;
38 };
39
40 };//loging
41
42 #define debug_loger (log_warper(ll_debug,__FILE__,__FUNCTION__,__LINE__))
43 #define debug_err_loger(error_code) (log_warper(ll_debug,__FILE__,__FUNCTION__,__LINE__,(error_code)))
44 #define info_loger (log_warper(ll_info))
45 #define warn_loger (log_warper(ll_warning))
46 #define err_loger (log_warper(ll_error,__FILE__,__FUNCTION__,__LINE__))
47 #define fata_loger (log_warper(ll_fatal_err,__FILE__,__FUNCTION__,__LINE__))
48 #endif // log_warper_h__

 

试验一把:

 1 #include "log_warper.h"
2 using namespace loging;
3
4 static const int messag_count=9;
5 const char* messages[9]={
6 "Well I've got two tickets to the game",
7 "It'd be great if I could take you to it this Sunday",
8 "And I'll walk you home",
9 "When the whole thing's done",
10 "If you're there I don't even care which team won",
11 "We could stop at the coffee shop",
12 "And make fun of the cops in the parking lot",
13 "And we could laugh as we both pretend",
14 "That we're not in love and that we're just good friends"
15 };
16
17 int _tmain(int argc, _TCHAR* argv[])
18 {
19
20 { info_loger.stream()<<"http://www.cnblogs.com/cheen";}
21 log_warper loger;
22 loger.reset (ll_info,__FILE__,__FUNCTION__,__LINE__);
23 loger.stream()<<"you got message"<<" => "<< std::endl;
24 for (int i=0;i<messag_count;i++){
25 loger.stream()<< std::string(messages[i])<< std::endl;
26 }
27 loger.finish ();
28
29 { info_loger.stream()<<"hello"<<"?";}
30 { warn_loger.stream()<<"hello"<<"?!";}
31 { warn_loger.stream()<<"are you free tonight"<<"?";}
32
33 loger.reset (ll_fatal_err);
34 loger.stream()
35 <<" Unhandled exception at: "
36 << std::hex <<std::showbase<< argv[0]<<std::endl
37 <<"for more information,see :"
38 <<"www.it_a_good_day_to_die.com";
39 loger.finish ();
40
41 return 0;
42 }



输出截图:

loging

 

代码:

loging-SRC