Traceability and monitoring of system events
defmodule MyApp.Service do
def critical_action(param1, param2) do
case MyApp.Repo.transaction(fun -> do_critical_action(param1, param2) end) do
{:ok, _result} -> :ok
{:error, _reason} -> :error
end
end
defp do_critical_action(param1, param2) do
# Implementation of critical action
end
end
The code is vulnerable because it doesn't log any information about the outcome of the critical action. If a critical action fails or an error occurs, there is no record of this event, making it difficult to identify and analyze the issue.
defmodule MyApp.Service do
require Logger
def critical_action(param1, param2) do
Logger.info("Starting critical action with #{param1}, #{param2}")
case MyApp.Repo.transaction(fun -> do_critical_action(param1, param2) end) do
{:ok, result} ->
Logger.info("Critical action succeeded with result: #{result}")
:ok
{:error, reason} ->
Logger.error("Critical action failed with reason: #{reason}")
:error
end
end
defp do_critical_action(param1, param2) do
# Implementation of critical action
end
end
This code is safe because it uses the Logger module to log the beginning and outcome of a critical action. If a critical action fails or an error occurs, there is a record of this event, making it easier to identify and analyze the issue.