This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the logging category.
Last Updated: 2024-11-21
I wrote a script for adding missing geocoordinate data to records in the database. I wanted its output to be clear about what was going on. My first draft was:
<?php
public function handle()
{
$advisors = Advisor::noGeoData();
echo(count($advisors) . " advisors need geodata");
$advisors_with_failure = [];
foreach ($advisors as $advisor) {
if ($advisor->add_geocode_info()) {
echo("Added geocoding for advisor:" . $advisor->id);
} else {
array_push($advisors_with_failure, $advisor->id);
echo("Failed to add geocoding for advisor:" .
$advisor->id);
}
}
if (count($advisors_with_failure) > 0) {
echo("\nThe following advisors had issues adding geocoding data:");
print_r($advisors_with_failure);
}
}
Unfortunately the print out was hard to parse, since no structure was apparent when looking at a cramped sequence of lines:
2 advisors need geodata
Added geocoding for advisor: 3
Failed to add geocoding for advisor 4
The following advisors had issues with adding geocoding data:
[4]
This sort of formatting might have been acceptable in program logs, where newlines are a waste, but not in program output, where understandability is the priority.
My goal in terms of readability would be something cleaner, like
2 advisors need geodata
Added geocoding for advisor: 3
ERROR: Failed to add geocoding for advisor 4
=====FINISHED======
The following advisors had issues with adding geocoding data:
[4]
The next version therefore included one or two newline characters at the end of each line, so as to space things out better.
<? php
public function handle()
{
$advisors = Advisor::noGeoData();
echo(count($advisors) . " advisors need geodata\n\n");
$advisors_with_failure = [];
foreach ($advisors as $advisor) {
if ($advisor->add_geocode_info()) {
echo("Added geocoding for advisor:" . $advisor->id . "\n");
} else {
array_push($advisors_with_failure, $advisor->id);
echo("ERROR: Failed to add geocoding for advisor:" .
$advisor->id . "\n");
}
}
echo("\n=====FINISHED=======");
if (count($advisors_with_failure) > 0) {
echo("\nThe following advisors had issues adding geocoding data:\n");
print_r($advisors_with_failure);
}
}
Ask yourself whether you are dealing with program output (which should optimize for readability) or program logs (which should optimize for parseability and parsimony). In the former case, make heavy use of newlines.