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  

90 comments:

  1. 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

    ReplyDelete


  2. 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

    ReplyDelete
  3. 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

    ReplyDelete
  4. 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

    ReplyDelete
  5. 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

    ReplyDelete
  6. 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

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

    Selenium Training in Chennai

    ReplyDelete
  8. 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

    ReplyDelete
  9. 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

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

    ExcelR Data Science Course in Bangalore

    ReplyDelete
  11. 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

    ReplyDelete
  12. 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

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete

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







    BIG DATA COURSE MALAYSIA

    ReplyDelete

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







    Big Data Course

    ReplyDelete
  16. 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

    ReplyDelete
  17. 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

    ReplyDelete
  18. 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.

    ReplyDelete
  19. 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

    ReplyDelete
  20. 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!

    ReplyDelete
  21. 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

    ReplyDelete
  22. 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

    ReplyDelete
  23. 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

    ReplyDelete
  24. 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

    ReplyDelete
  25. 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

    ReplyDelete
  26. 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



    ReplyDelete
  27. 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

    ReplyDelete
  28. 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

    ReplyDelete
  29. 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

    ReplyDelete
  30. 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

    ReplyDelete

  31. "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

    ReplyDelete
  32. 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

    ReplyDelete
  33. 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

    ReplyDelete
  34. 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

    ReplyDelete

  35. 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

    ReplyDelete
  36. 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

    ReplyDelete
  37. 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

    ReplyDelete
  38. 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

    ReplyDelete

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

    ReplyDelete
  40. 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

    ReplyDelete

  41. 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

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

    ReplyDelete
  43. 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

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

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

    ReplyDelete
  46. 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.

    ReplyDelete
  47. 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


    ReplyDelete
  48. 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

    ReplyDelete
  49. 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

    ReplyDelete
  50. 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

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

    ReplyDelete
  52. 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

    ReplyDelete
  53. 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

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

    ReplyDelete
  55. 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

    ReplyDelete
  56. 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



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

    ReplyDelete
  58. 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.

    ReplyDelete
  59. digital marketing training malaysiaMay 5, 2022 at 3:24 AM

    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

    ReplyDelete
  60. 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

    ReplyDelete
  61. business analytics course in patnaMay 26, 2022 at 2:13 AM

    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>

    ReplyDelete
  62. "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"

    ReplyDelete
  63. 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

    ReplyDelete
  64. 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

    ReplyDelete
  65. 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

    ReplyDelete
  66. data science training in lucknowJuly 5, 2022 at 12:55 AM

    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

    ReplyDelete
  67. 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

    ReplyDelete
  68. 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

    ReplyDelete
  69. 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

    ReplyDelete
  70. 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

    ReplyDelete