Rust: Custom Logger with time-stamp, file name and line number

Rust language has a built-in support for logging.  The default logger logs the log level, module name and log message which are not sufficient for troubleshooting. Fortunately,  Rust log crate does allow overriding with a custom logger.

I wanted to log the current time-stamp,  module name, function name and line number and posted a question on Reddit on how do log these information. Based on the answers, Rust does have support for module, line and file name but no support for function name. 

To implement the Custom Logger, I looked at the default logger implementation in  lib.rs in log crate and realized that LogRecord does support file-name and line number but while logging, it does not use it.

 pub fn log(level: u32, loc: &'static LogLocation, args: &fmt::Arguments) {  
    // Test the literal string from args against the current filter, if there  
    // is one.  
    match unsafe { FILTER.as_ref() } {  
      Some(filter) if !filter.is_match(args.to_string().as_slice()) => return,  
      _ => {}  
    }  
    // Completely remove the local logger from TLS in case anyone attempts to  
    // frob the slot while we're doing the logging. This will destroy any logger  
    // set during logging.  
    let mut logger = LOCAL_LOGGER.with(|s| {  
      s.borrow_mut().take()  
    }).unwrap_or_else(|| {  
      box DefaultLogger { handle: io::stderr() } as Box<Logger + Send>  
    });  
    logger.log(&LogRecord {  
      level: LogLevel(level),  
      args: args,  
      file: loc.file,  
      module_path: loc.module_path,  
      line: loc.line,  
    });  
    set_logger(logger);  
  }  


To support the logging of function name, there is a pending RFC/Pull Request, hope that gets implemented before Rust 1.0.

For time being, let manage without function name and implement our custom logger.

 #![feature(phase)]  
 #[phase(plugin, link)]extern crate log;  
 #[phase(plugin, link)]extern crate time;  
 /// import  
 use log::{Logger,LogRecord,LogLevel,LogLocation, set_logger};  
 use std::io::{ LineBufferedWriter, stdio, stderr} ;  
 /// Custom Logger  
 struct CustomLogger {  
    handle: LineBufferedWriter<stdio::StdWriter>,  
  }  
 /// Implements Logger trait for Custom Logger which support logging timestamp, file name and line number  
 /// in addition to log level, module path and message.  
 impl Logger for CustomLogger {  
    fn log(&mut self, record: &LogRecord) {  
      match writeln!(&mut self.handle,  
             "{}:{}:{}:{}:{} {}",  
             time::strftime("%Y-%m-%d %H:%M:%S %Z", &time::now()).unwrap(),  
             record.level,  
             record.module_path,  
             record.file,  
             record.line,  
             record.args) {  
        Err(e) => panic!("failed to log: {}", e),  
        Ok(()) => {}  
      }  
    }  
  }  
 ///main   
 fn main() {  
       log::set_logger(box CustomLogger { handle: stderr() } );  
   debug!("Debug message");  
   warn!("Warn message");  
   error!("Error message");  
 }  


Here is output:
 RUST_LOG=debug ./target/custom-logger  
 2014-12-17 09:23:48 :DEBUG:custom-logger:/projects/rust/custom-logger/src/main.rs:32 Debug message  
 2014-12-17 09:23:48 :WARN:custom-logger:/projects/rust/custom-logger/src/main.rs:33 Warn message  
 2014-12-17 09:23:48 :ERROR:custom-logger:/projects/rust/custom-logger/src/main.rs:34 Error message  

NOTE:  I notice it doesn't print the timezone and leave an empty space.

Once I figure out the timezone issue and logging function name , it will look like below which is much better than file with being repeated.

RUST_LOG=debug ./target/custom-logger  
 2014-12-17 09:23:48 EST:DEBUG:custom-logger::main::32 Debug message  
 2014-12-17 09:23:48 EST:WARN:custom-logger::main:33 Warn message  
 2014-12-17 09:23:48 EST:ERROR:custom-logger::main:34 Error message  

61 comments:

karthireva said...

Thanks for sharing article like this. The way

you have stated everything above is quite

awesome. Keep blogging like this. Thanks a lot.


PHP Training in Chennai

karthireva said...



Truely a very good article on how to handle the future technology. After reading your post,thanks for taking the time to discuss this content.

Dot Net Training in Chennai ECR

Akshaysri said...

I just see the post i am so happy the post of information's.So I have really enjoyed and reading your blogs for these posts.Any way I’ll be subscribing to your feed and I hope you post again soon.
GMAT coaching chennai

Stepherd said...

Being new to the blogging world I feel like there is still so much to learn. Your tips helped to clarify a few things for me as well as giving..

Manpower Consultancy in Chennai

Unknown said...

I have seen that all will say the same thing repeatedly. But in your blog, I had a chance to get some useful and unique information. I would like to suggest your blog in my dude circle. please keep on updates. hope it might be much useful for us. keep on updating.
SEO Training in Chennai

Unknown said...

Thank you for sharing such a nice and interesting blog with us. I have seen that all will say the same thing repeatedly. But in your blog, I had a chance to get some useful and unique information. I would like to suggest your blog in my dude circle.
SEO Company in Chennai

Unknown said...

Finding the time and actual effort to create a superb article like this is great thing. I’ll learn many new stuff right here! Good luck for the next post buddy..
Jobs in Noida
Jobs in Pune

aashisiva said...

I must thank you for the efforts you have put in penning this site. I am hoping to check out the same high-grade content by you later on as well. In truth, your creative writing abilities has inspired me to get my own, personal blog now..
SEO Training in Chennai
Selenium Training in Chennai
Web Designing Training in Chennai

Anonymous said...


Really Good blog post.provided a helpful information.keep updating...
Digital marketing company in Chennai

mahalyasree said...

It’s the best time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I want to suggest you few interesting things or suggestions.You can write next articles referring to this article. I desire to read even more things about it..
Office Interior Designers in Bangalore
Office Interior Designers in Hyderabad

Unknown said...

Thanks for your wonderful information..
SAP Basis Training in Chennai

Tamil said...

Wonderful blog and very useful.Thanks for sharing this valuable information...
SAP Basis Training in Chennai

Unknown said...

Its an awesome article. written in very creative way and it also conveys useful information.

Selenium Training in Chennai

Unknown said...

Its really an Excellent post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog. posts. I hope you post again soon.

Selenium Training in Chennai

Unknown said...

Omrdeals.in is an online platform that allows people to find offers and the greatest deals in and around OMR. It is the directory of the business in and around omr. It helps internet users to surf the required deals and offers.

Offers in Chennai

Unknown said...

Thanks for the informative article.This is one of the best tips in my life. I have in quite some time.Nicely written and great info.I really cannot thank you enough for sharing.

Apartments in Chennai

afiah b said...

It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
Java training in Bangalore | Java training in Jaya nagar

Java training in Bangalore | Java training in Electronic city

Java training in Chennai | Java training institute in Chennai | Java course in Chennai

Java training in USA

Mounika said...

The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
python course in pune
python course in chennai
python course in Bangalore

Unknown said...

This is ansuperior writing service point that doesn't always sink in within the context of the classroom. In the first superior writing service paragraph you either hook the reader's interest or lose it. Of course your teacher, who's getting paid to teach you how to write an good essay, 
Data Science training in Chennai | Data Science Training Institute in Chennai
Data science training in Bangalore | Data Science Training institute in Bangalore
Data science training in pune | Data Science training institute in Pune
Data science online training | online Data Science certification Training-Gangboard
Data Science Interview questions and answers

Unknown said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
Best Devops training in sholinganallur
Devops training in velachery
Devops training in annanagar
Devops training in tambaram

genga g said...

Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.

angularjs Training in chennai

angularjs-Training in tambaram

angularjs-Training in sholinganallur

angularjs-Training in velachery

angularjs-Training in pune

angularjs Training in bangalore

tamilsasi said...

Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you.
Keep update more information..


Selenium training in bangalore
Selenium training in Chennai
Selenium training in Bangalore
Selenium training in Pune
Selenium Online training
Selenium interview questions and answers

SRI said...

Read all the information that i've given in above article. It'll give u the whole idea about it.
microsoft azure training in bangalore
rpa training in bangalore
best rpa training in bangalore
rpa online training

prasadarao said...

Very nice information, it is valuable and useful to so many people. It gives the beautiful knowledge especially to the technical people.
hardware and networking course in Hyderabad
mobile repairing course in Hyderabad
laptop repairing course in Hyderabad
chip level repairing course in Hyderabad
chip level training in Hyderabad
printer repair service in Hyderabad
laptop repairing institute in hyderabad
mobile repairing institute in hyderabad
laptop repairing course
mobile repairing course
hardware and networking course
chip level repairing course
chip level training
laptop repairing in hyderabad
mobile repairing in hyderabad
laptop repairing
mobile repairing

kingdom said...

Deployment and implementation of Robotic Process Automation are the toughest tasks in the latest technology and one of the most occurred
RPA challenges as well. It affects the whole level of processes. All the processes go through different functionalities like individual and
company hierarchy. It also depends upon different companies on different levels.

BLUEPRISM RPA Training in OMR Chennai

Aaditya said...

Pretty good post. This is a wonderful article, Given so much info in it, keep sharing.

ExcelR Data Science Course in Bangalore

zaintech99 said...

I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.
date analytics certification training courses

Priyanka said...

Attend The Python training in bangalore From ExcelR. Practical Python training in bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python training in bangalore.
python training in bangalore

Nithya Sri said...
This comment has been removed by the author.
malaysiaexcelr01 said...


I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.







BIG DATA COURSE MALAYSIA

istiaq ahmed said...

This website and I conceive this internet site is really informative ! Keep on putting up!
Data Science Course in Pune

malaysiaexcelr01 said...


I am looking for and I love to post a comment that "The content of your post is awesome" Great work!







Big Data Course

data science analytics rakshi said...

I finally found great post here.I will get back here. I just added your blog to my bookmark sites. thanks.Quality posts is the crucial to invite the visitors to visit the web page, that's what this web page is providing.data science course in dubai

data science analytics rakshi said...

I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!data science course in dubai

zaintech99 said...

This is also a very good post which I really enjoyed reading. It is not every day that I have the possibility to see something like this..
www.technewworld.in
How to Start A blog 2019
Eid AL ADHA

saketh said...

I feel very grateful that I read this. It is very helpful and very informative and I Python classes in pune really learned a lot from it.

jaanu said...

I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!
big data course malaysia

lucy88 said...

This is also a very good post which I really enjoyed reading. It is not every day that I have the possibility to see something like this,
Great website

Bushraah88 said...

Really appreciate this wonderful post that you have provided for us.Great site and a great topic as well i really get amazed to read this. Its really good, Love it.

Data anlytic said...

Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us
You will get an introduction to the Python programming language and understand the importance of it. How to download and work with Python along with all the basics of Anaconda will be taught. You will also get a clear idea of downloading the various Python libraries and how to use them.
Topics
About ExcelR Solutions and Innodatatics
Do's and Don’ts as a participant
Introduction to Python
Installation of Anaconda Python
Difference between Python2 and Python3
Python Environment
Operators
Identifiers
Exception Handling (Error Handling)
Excelr Solutions

jaanu said...

Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!
big data course malaysia

datasciencecourse said...

Such a great and informative article.
You just made my day thanks for sharing this article.

data science course singapore is the best data science course

Bushraah88 said...

Great post i must say and thanks for the information. Education is definitely a sticky subject. it is still among the leading topics of our time. I appreciate your post and looking for more.
, technewworld.in.

datasciencecertification said...

I love your article so much. Good job
ExcelR is a global leader delivering a wide gamut of management and technical training over 40 countries. We are a trusted training delivery partner of 350+ corporate clients and universities across the globe with 28,000+ professionals trained across various courses. With over 20 Franchise partners all over the world, ExcelR helps individuals and organisations by providing courses based on practical knowledge and theoretical concepts.

Excelr Solutions

Unknown said...

I love your article so much. Good job
Participants who complete the assignments and projects will get the eligibility to take the online exam. Thorough preparation is required by the participants to crack the exam. ExcelR's faculty will do the necessary handholding. Mock papers and practice tests will be provided to the eligible participants which help them to successfully clear the examination.

Excelr Solutions

seoexpert said...

Nice Post...I have learn some new information.thanks for sharing.
Click here for ExcelR Business Analytics Course

Priyanka said...

Attend The Data Analytics Course in Bangalore From ExcelR. Practical Data Analytics Course in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analytics Course in Bangalore.
ExcelR Data Analytics Course in Bangalore

Unknown said...

I like you article. if you you want to saw Sufiyana Pyaar Mera Star Bharat Serials Full
Sufiyana Pyaar Mera

ExcelR Pune said...

Really thanks for sharing...This blog is awesome very informative..
ExcelR Machine Learning

Customer relationship management said...

Wow it is really wonderful and awesome thus it is veWow, it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot.

python training in bangalore

python courses in bangalore

python classes in bangalore

python training institute in bangalore

python course syllabus

best python training

python training centers

Customer relationship management said...

This is the exact information I am been searching for, Thanks for sharing the required infos with the clear update and required points. To appreciate this I like to share some useful information.

aws training in bangalore

aws courses in bangalore

aws classes in bangalore

aws training institute in bangalore

aws course syllabus

best aws training

aws training centers

Customer relationship management said...

It is very good and useful for students and developer.Learned a lot of new things from your post Good creation,thanks for give a good information at sap crm.

devops training in bangalore

devops courses in bangalore

devops classes in bangalore

devops training institute in bangalore

devops course syllabus

best devops training

best devops training

Customer relationship management said...

I have to voice my passion for your kindness giving support to those people that should have guidance on this important matter.

sap s4 hana training in bangalore

sap s4 hana courses in bangalore

sap s4 hana classes in bangalore

sap s4 hana training institute in bangalore

sap s4 hana course syllabus

best sap s4 hana training

sap s4 hana training centers

Customer relationship management said...

Excellent post for the people who really need information for this technology.

sap simplefinance training in bangalore

sap simplefinance courses in bangalore

sap simplefinance classes in bangalore

sap simplefinance training institute in bangalore

sap simplefinance course syllabus

best sap simplefinance training

sap simplefinance training centers

Softgen Infotech said...

Thank you for sharing such a nice post!

Looking for Software Training in Bangalore , learn from Softgen Infotech Software Courses on online training and classroom training. Join today!

Dennis said...

Thanks for your blog!!.
JAVA Development Services
HR Pay Roll Software
SAP Software Services
Hotel Billing Software
Web Design Company
Hospital Management Software

watson said...

Great post!I am actually getting ready to across this information,i am very happy to this commands.Also great blog here with all of the valuable information you have.Well done,its a great knowledge. Real Time Experts training center bangalore

watson said...

Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site.Real Time Experts Training in Bangalore

watson said...

Great post!I am actually getting ready to across this information,i am very happy to this commands.Also great blog here with all of the valuable information you have.Well done,its a great knowledge.student review for Realtime Experts marathahalli bangalore

watson said...

Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site. Real Time Experts Training in Bangalore center address bangalore

Never Ending Footsteps said...

data science course bangalore is the best data science course