Home » Ruby programming

Creating a Custom Error logger in Ruby

Ruby | Custom Error Logger: In this tutorial, we are going to learn about the custom logger in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on November 21, 2019

We have gone through Exception handling in Ruby. We can handle exceptions with the help of begin...rescue block. Handling Exceptions or Errors is really because if you don't do so, you would not be able to process the rest of the code lines. While creating some kind of application, you may need to keep the type of Error occurred or Error string in a file for future reference. In this program, we will design a code that will help us in creating a custom error log that will be storing all the errors occurred while the execution of our code. Following is the code which will tell you how you can create a custom error log or a txt file. We will make use of file handling for the purpose.

def log_error e
  File.open('error1.txt', 'a') do |file|
    file.puts e
  end
end

begin
  p nil + 100
rescue StandardError => e
  log_error("Error: #{e} occured at #{Time.now}")
end

begin
  p 81 / 0
rescue StandardError => e
  log_error("Error: #{e} occured at #{Time.now}")
end

begin
  p 81 / nil
rescue StandardError => e
  log_error("Error: #{e} occured at #{Time.now}")
end

Error logger file:

Python | Create Error Logger

Explanation:

In the above code, we have created an error logger. log_error function is playing the main role here. We are passing the error string as an argument inside this function. Inside it, we are opening a file "error1.txt" in append mode because we don't want our file to get overwritten after each function call. We are printing error string in the file with the help of file.puts method.

In the main, we are executing three statements inside begin...rescue block. We know that all these three statements will provide us some kind of error so we are handling the errors. We are invoking log_error function and passing a string that contains the name of the error along with the time at which it has occurred. You can observe the "error1.txt" file which is having all the name of errors which occur along with the time at which Interpreter had to face them. This is how we handle errors in Real-world programming.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.