Home »
Ruby Tutorial
Creating a Custom Error logger in Ruby
By IncludeHelp Last updated : December 03, 2024
Overview of Exception Handling
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.
Importance of Logging Errors
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.
Creating a Custom Error Log File
To store errors in a text file, we can leverage Ruby's file-handling capabilities. Below is the code that demonstrates how to create a custom error log file:
Example
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
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.