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  

94 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

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

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

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

Unknown said...

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

Selenium Training 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

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

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

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

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

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

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.

Maisha Thasin 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

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!

Realtime Experts 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

Anonymous said...

Its as if you had a great grasp on the subject matter, but you forgot to include your readers. Perhaps you should think about this from more than one angle.
For more information: https://360digitmg.com/course/professional-certification-in-business-analytics
https://360digitmg.com/course/certification-program-in-data-science
https://360digitmg.com/course/data-visualization-using-tableau
https://360digitmg.com

course on big data analytics said...

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.



course on big data analytics

tejaswini said...

I feel really happy to have seen your webpage and look forward to so many more entertaining times reading here. Thanks once more for all the details.

data science course
360DigiTMG

tejaswini said...

This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the good work. I have been meaning to write something like this on my website and you have given me an idea.
data science course in malaysia
360DigiTMG

nisha said...

Thanks For Updating the Blog.

Data Science Training Course In Chennai | Data Science Training Course In Anna Nagar | Data Science Training Course In OMR | Data Science Training Course In Porur | Data Science Training Course In Tambaram | Data Science Training Course In Velachery

nikhil reddy said...

Hi, Thanks for sharing wonderful articles...

AI Training In Hyderabad

akash said...

knew where I could get a captcha plugin for my comment form? I’m using the same blog platform like yours, and I’m having difficulty finding one? Thanks a lot...
Microsoft Windows Azure Training | Online Course | Certification in chennai | Microsoft Windows Azure Training | Online Course | Certification in bangalore | Microsoft Windows Azure Training | Online Course | Certification in hyderabad | Microsoft Windows Azure Training | Online Course | Certification in pune

rocky said...

I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information . thank you so much.
Python Training in Chennai

Python Training in Bangalore

Python Training in Hyderabad

Python Training in Coimbatore

Python Training

python online training

python flask training

python flask online training



Data Science Course in Hyderabad said...

very interesting post.this is my first time visit here.i found so many interesting stuff in your blog especially its discussion..thanks for the post!
Data Science Course in Hyderabad | Data Science Training in Hyderabad

devi said...

Such a very useful article. Very interesting to read this article. I would like to thank you for the efforts you had made for writing this awesome article.I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it. Data Science Training In Chennai | Certification | Data Science Courses in Chennai | Data Science Training In Bangalore | Certification | Data Science Courses in Bangalore | Data Science Training In Hyderabad | Certification | Data Science Courses in hyderabad | Data Science Training In Coimbatore | Certification | Data Science Courses in Coimbatore | Data Science Training | Certification | Data Science Online Training Course

Sages Marketing said...

https://www.damiengrantlendingteam.com/
https://www.damiengrantlendingteam.com/
https://www.damiengrantlendingteam.com/
https://www.damiengrantlendingteam.com/
https://www.damiengrantlendingteam.com/
https://www.damiengrantlendingteam.com/
https://www.damiengrantlendingteam.com/
https://www.damiengrantlendingteam.com/

deiva 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.
java training in chennai

java training in omr

aws training in chennai

aws training in omr

python training in chennai

python training in omr

selenium training in chennai

selenium training in omr

Jayalakshmi 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.
oracle training in chennai

oracle training in tambaram

oracle dba training in chennai

oracle dba training in tambaram

ccna training in chennai

ccna training in tambaram

seo training in chennai

seo training in tambaram

IoT Course in Raipur - 360DigiTMG said...

360DigiTMG Provides the best Artificial Intelligence Course in Raipur with 100% Job Placement Assistance. Get International Artificial Intelligence Course Certification from Malaysia and India.

360DigiTMG Artificial Intelligence Course
Artificial Intelligence training in raipur
Artificial Intelligence online course
Artificial Intelligence Course in raipur

Jackie Co Kad said...

Great Article
Artificial Intelligence Projects

Project Center in Chennai



JavaScript Training in Chennai

JavaScript Training in Chennai

shiny 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

sap training in chennai

sap training in annanagar

azure training in chennai

azure training in annanagar

cyber security course in chennai

cyber security course in annanagar

ethical hacking course in chennai

ethical hacking course in annanagar

jeni said...

I simply wanted to thank you so much again. I am not sure the things that I might have gone through without the type of hints revealed by you regarding that situation.

oracle training in chennai

oracle training in velachery

oracle dba training in chennai

oracle dba training in velachery

ccna training in chennai

ccna training in velachery

seo training in chennai

seo training in velachery


Data Science training - 360DigiTMG said...

Extraordinary blog went amazed with the content they have developed in a very descriptive manner. Hope you deliver the same near the future as well. Gratitude to the blogger for the efforts.

360DigiTMG Cloud Computing Course

360digitmgdelhi said...

I looked at some very important and to maintain the length of the strength you are looking for on your website
data science course in Delhi

360DigiTMG said...


"I can set up my original thought from this post. It gives all around data. A commitment of gratefulness is all together for this essential data for all,

"
HRDF training

360DigiTMG PMP Certification said...

On the off chance that your searching for Online Illinois tag sticker restorations, at that point you have to need to go to the privileged place.
360DigiTMG PMP Certification

tejaswini said...

I have bookmarked your site since this site contains significant data in it. You rock for keeping incredible stuff. I am a lot of appreciative of this site.
data science training

360digitmgdelhi said...

This is a great post I saw thanks to sharing. I really want to hope that you will continue to share great posts in the future.
artificial intelligence course in delhi

Rohini said...


Its as if you had a great grasp on the subject matter, but you forgot to include your readers. Perhaps you should think about this from more than one angle.
machine learning courses in bangalore

360DigiTMG said...

I curious more interest in some of them hope you will give more information on this topics in your next articles.
data science institute in hyderabad

Data Science training - 360DigiTMG said...

Tremendous blog quite easy to grasp the subject since the content is very simple to understand. Obviously, this helps the participants to engage themselves in to the subject without much difficulty. Hope you further educate the readers in the same manner and keep sharing the content as always you do.

Data Science training

PMP certification said...

The writer is amped up for purchasing wooden furniture on the web and his examination of the best wooden furniture has accomplished the blueprint of this article.
PMP certification

saketh321 said...


Very educating story, saved your site for hopes to read more! ExcelR Data Analytics Course

360digiTMG Training said...

We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work
Digital Marketing Training Institutes in Hyderabad

360DigiTMG_Gurgaon said...

"Thank you very much for your information.
From,
"data science course in gurgaon

360digiTMG Training said...


I think I have never seen such blogs before that have completed things with all the details which I want. So kindly update this ever for us.
Digital Marketing Course

Anonymous said...

This blog post is very much informative, thanks for sharing.
SEO Training In Hyderabad

traininginstitute said...

I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoy every little bit of it and I have you bookmarked to check out new stuff you post.

business analytics course

traininginstitute said...

I am genuinely thankful to the holder of this web page who has shared this wonderful paragraph at at this place.
business analytics course

data scientist course said...

Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one.
data scientist training and placement

3RI Technologies said...

Great content shared, keep sharing. Thanks for writing!

Data Science Training in Pune

NoveltyDMVExperts said...

Hi there I am so delighted I found your weblog, I really found you by accident,
while I was researching on Bing for something else, Regardless I am here now and would just QUALITY UNDETECTED ORIGINAL FAKE DRIVING LICENCE like to say thank you for a fantastic post and a all round entertaining blog (I also love the theme/design), I don’t have time to go through it all at the minute but I have bookmarked it and also added your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the excellent job.

Digital Marketing Training in Bangalore said...

I have voiced some of the posts on your website now, and I really like your blogging style. I added it to my list of favorite blogging sites and will be back soon ...

Digital Marketing Training in Bangalore


traininginstitute said...

I have read your excellent post. This is a great job. I have enjoyed reading your post first time. I want to say thanks for this post. Thank you...
data scientist certification malaysia

Anonymous said...

Amazing Articles ! I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.

Data science course in pune

Best Software Development Company said...

Hey there

Nice article, Thanks for sharing

Software Development company
Mobile app development company
Best web development company

Maneesha said...

I’ve read some good stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you put to create such a great informative website.
data scientist training and placement

traininginstitute said...

I truly like you're composing style, incredible data, thankyou for posting.
data scientist course

Pallavireddy said...

i am glad to discover this page : i have to thank you for the time i spent on this especially great reading !! i really liked each part and also bookmarked you for new information on your site.
artificial intelligence course in nashik

Maneesha said...

Writing with style and getting good compliments on the article is quite hard, to be honest.But you've done it so calmly and with so cool feeling and you've nailed the job. This article is possessed with style and I am giving good compliment. Best!
aws online training in hyderabad

traininginstitute said...

Impressive. Your story always bring hope and new energy. Keep up the good work.
data scientist course

Maneesha said...

Wonderful illustrated information. I thank you for that. No doubt it will be very useful for my future projects. Would like to see some other posts on the same subject!
data science coaching in hyderabad

Data Science said...

Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing.data scientist course in warangal



Pavithra Devi said...

This post is so interactive and informative.keep update more information...
Salesforce Training in Tambaram
Salesforce Training in Chennai

360DigiTMG said...

Thanks for such a great post and the review, I am totally impressed! Keep stuff like this coming.
business analytics course in hyderabad

Career Academic institute said...

It's like you've got the point right, but forgot to include your readers. Maybe you should think about it from different angle
Data Scientist Course in Kolkata s.

manasha said...

Great post. keep sharing such a worthy information.
Blue Prism Training in Chennai
Blue Prism Online Training

digital marketing training malaysia said...

I will truly value the essayist's decision for picking this magnificent article fitting to my matter.Here is profound depiction about the article matter which helped me more. digital marketing training malaysia

Anonymous said...

This article will present a closer look at data science courses that give you a comprehensive look at the field. So let's get started.

data science course in borivali

business analytics course in patna said...

360DigiTMG offers the best Data Analytics courses in the market with placement assistance. Enroll today and fast forward your career.
<a href="https://360digitmg.com/india/business-analytics-training-in-patna''>business analytics course in patna</a>

radha 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
how to learn matlab |computer science summer internships |iot online courses |number 1 summer and winter internship training and workshop service provider in india. |online c programming classes

|machine learning training | data science course fees in coimbatore |internship opportunities for engineering students |electronic engineering summer internships |wordpress training in chennai

Swarnalatha said...

"If you are also one of them and want to know what the companies demand from the data scientists to do in their organization, you have come to the right place.data science course in kolkata"

Career Academic institute said...

Are you worried that joining in a top-rated Data Science course will burn a hole in your pocket, fret not 360DigiTMG offers Data Science courses that are pocket friendly. Enroll now to learn more about the course and fee details.

Data Science in Bangalore

Professional Academic Institute said...

With multitude of career opportunities opening up in Data Science domain and more and more IT professionals are looking for best Data Science courses to start their Data Sciences career. 360DigiTMG is the best place to start your technical training. As we are equipped with world-class curriculum to suit all your technical needs.

Data Science Course in Bangalore with Placement

Career Program and Skill Development said...

Data Science is a growing domain with multitude of job opportunities, start your Data Scientsist Course today with 360DigiTMG and become a Data Scientist

Best Data Science Training institute in Bangalore

data science training in lucknow said...

When you start learning the discovery of data insight courses, you will have to develop an understanding of detecting complex behaviors and patterns of data.
data science training in lucknow

Career Programs Excellence said...

Boost your professional reputation with a surefire way to pick up some impressive new skills in data science by registering for the Data science courses near me. Learn to collect, clean, and analyze data with tools like Hadoop and Spark. Learn to develop algorithms and build models in machine learning to optimize product performance and gross profit for your organization. Become an expert in techniques like Data Mining, Data Cleansing, and Data Exploring that help refine data, making it possible to present it in an understandable format.

Data Science Course in Bangalore

Samia Beel said...

Hotspot Shield Business Crack is a powerful VPN application that safeguards your PC's information while utilizing a shaky remote association. Hotspot Shield Elite Full Crack

anuaradhya said...

Great to become visiting your weblog once more, it has been a very long time for me.
Pleasantly this article i've been sat tight for such a long time. I will require this post to add up to my task in the school,
and it has identical subject along with your review. Much appreciated, great offer.
data analytics courses malaysia

deekshitha said...

Data Science is a competitive field with a bright future. Enroll in a Data Science course with 360DigiTMG today to quickly become a Data Scientist.data science course institute in nagpur

DigiperformSeo said...

Thank you for your valuable answer. Want to know more about Top 8 Best Data Science Course In Lucknow

RICHA said...

This is such a practical guide! Rust is such a powerful tool, and your example really brings its potential to life. Thanks for simplifying it so well.
Data science courses in the Netherlands

Neelkbh said...


This is a great insight into extending Rust's default logging system! It's interesting to see how Rust's log crate allows for customization, even though it lacks function name support by default. The approach of implementing a custom logger with file and line information is a practical solution for troubleshooting. I’m looking forward to the eventual addition of function name logging through the RFC—this will be a huge benefit for developers needing detailed logs in their applications.
Data science Courses in City of Westminster

Neel KBH
kbhneel@gmail.com

Abar Singh said...

The use of Rust for building a customer logger system is a fascinating choice. It’s great to see how Rust’s performance benefits real-time systems like this. Looking forward to more technical posts!
Data science courses in france

iim skills Diksha said...

This post provides a clear and practical guide to implementing a custom logger in Rust, addressing the limitations of the default logger. The inclusion of time-stamp, file name, and line number enhances troubleshooting and debugging capabilities significantly. Overall, this is an informative post that demonstrates advanced logging techniques in Rust, making it a valuable resource for developers!
Data science Courses in Ireland