psu: Convert logging to lg2

Change-Id: I223d888a7c8f8bfa64c1fbdf3170fa511fb696d8
Signed-off-by: George Liu <liuxiwei@ieisystem.com>
diff --git a/src/psu/PSUEvent.cpp b/src/psu/PSUEvent.cpp
index 438faa2..353e1f1 100644
--- a/src/psu/PSUEvent.cpp
+++ b/src/psu/PSUEvent.cpp
@@ -31,7 +31,6 @@
 #include <array>
 #include <chrono>
 #include <cstddef>
-#include <iostream>
 #include <memory>
 #include <set>
 #include <stdexcept>
@@ -56,7 +55,7 @@
 
     if (!eventInterface->initialize())
     {
-        std::cerr << "error initializing event interface\n";
+        lg2::error("error initializing event interface");
     }
 
     std::shared_ptr<std::set<std::string>> combineEvent =
@@ -199,7 +198,7 @@
     }
     if (!buffer)
     {
-        std::cerr << "Buffer was invalid?";
+        lg2::error("Buffer was invalid?");
         return;
     }
 
@@ -248,7 +247,7 @@
     }
     if (!buffer)
     {
-        std::cerr << "Buffer was invalid?";
+        lg2::error("Buffer was invalid?");
         return;
     }
     // null terminate the string so we don't walk off the end
@@ -276,7 +275,7 @@
     {
         if (errCount == warnAfterErrorCount)
         {
-            std::cerr << "Failure to read event at " << path << "\n";
+            lg2::error("Failure to read event at '{PATH}'", "PATH", path);
         }
         updateValue(0);
         errCount++;
@@ -324,14 +323,14 @@
                 // Fan Failed has two args
                 if (deassertMessage == "OpenBMC.0.1.PowerSupplyFanRecovered")
                 {
-                    lg2::info("{EVENT} deassert", "EVENT", eventName,
+                    lg2::info("'{EVENT}' deassert", "EVENT", eventName,
                               "REDFISH_MESSAGE_ID", deassertMessage,
                               "REDFISH_MESSAGE_ARGS",
                               (psuName + ',' + fanName));
                 }
                 else
                 {
-                    lg2::info("{EVENT} deassert", "EVENT", eventName,
+                    lg2::info("'{EVENT}' deassert", "EVENT", eventName,
                               "REDFISH_MESSAGE_ID", deassertMessage,
                               "REDFISH_MESSAGE_ARGS", psuName);
                 }
@@ -345,7 +344,7 @@
     }
     else
     {
-        std::cerr << "PSUSubEvent asserted by " << path << "\n";
+        lg2::error("PSUSubEvent asserted by '{PATH}'", "PATH", path);
 
         if ((!*assertState) && ((*asserts).empty()))
         {
@@ -355,14 +354,14 @@
                 // Fan Failed has two args
                 if (assertMessage == "OpenBMC.0.1.PowerSupplyFanFailed")
                 {
-                    lg2::warning("{EVENT} assert", "EVENT", eventName,
+                    lg2::warning("'{EVENT}' assert", "EVENT", eventName,
                                  "REDFISH_MESSAGE_ID", assertMessage,
                                  "REDFISH_MESSAGE_ARGS",
                                  (psuName + ',' + fanName));
                 }
                 else
                 {
-                    lg2::warning("{EVENT} assert", "EVENT", eventName,
+                    lg2::warning("'{EVENT}' assert", "EVENT", eventName,
                                  "REDFISH_MESSAGE_ID", assertMessage,
                                  "REDFISH_MESSAGE_ARGS", psuName);
                 }
diff --git a/src/psu/PSUSensor.cpp b/src/psu/PSUSensor.cpp
index 4d410fe..2ba212e 100644
--- a/src/psu/PSUSensor.cpp
+++ b/src/psu/PSUSensor.cpp
@@ -26,13 +26,13 @@
 #include <boost/asio/error.hpp>
 #include <boost/asio/io_context.hpp>
 #include <boost/asio/random_access_file.hpp>
+#include <phosphor-logging/lg2.hpp>
 #include <sdbusplus/asio/connection.hpp>
 #include <sdbusplus/asio/object_server.hpp>
 
 #include <array>
 #include <chrono>
 #include <cstddef>
-#include <iostream>
 #include <limits>
 #include <memory>
 #include <stdexcept>
@@ -65,11 +65,13 @@
     std::string unitPath = sensor_paths::getPathForUnits(sensorUnits);
     if constexpr (debug)
     {
-        std::cerr << "Constructed sensor: path " << path << " type "
-                  << objectType << " config " << sensorConfiguration
-                  << " typename " << unitPath << " factor " << factor << " min "
-                  << min << " max " << max << " offset " << offset << " name \""
-                  << sensorName << "\"\n";
+        lg2::debug(
+            "Constructed sensor - path: {PATH}, type: {TYPE}, config: {CONFIG}, "
+            "typename: {TYPENAME}, factor: {FACTOR}, min: {MIN}, max: {MAX}, "
+            "offset: {OFFSET}, name: {NAME}",
+            "PATH", path, "TYPE", objectType, "CONFIG", sensorConfiguration,
+            "TYPENAME", unitPath, "FACTOR", factor, "MIN", min, "MAX", max,
+            "OFFSET", offset, "NAME", sensorName);
     }
     if (pollRate > 0.0)
     {
@@ -159,7 +161,7 @@
 
     if (buffer == nullptr)
     {
-        std::cerr << "Buffer was invalid?";
+        lg2::error("Buffer was invalid?");
         return;
     }
 
@@ -189,7 +191,7 @@
     waitTimer.async_wait([weakRef](const boost::system::error_code& ec) {
         if (ec == boost::asio::error::operation_aborted)
         {
-            std::cerr << "Failed to reschedule\n";
+            lg2::error("Failed to reschedule");
             return;
         }
         std::shared_ptr<PSUSensor> self = weakRef.lock();
@@ -207,20 +209,20 @@
 {
     if (err == boost::asio::error::operation_aborted)
     {
-        std::cerr << "Read aborted\n";
+        lg2::error("Read aborted");
         return;
     }
     if ((err == boost::system::errc::bad_file_descriptor) ||
         (err == boost::asio::error::misc_errors::not_found))
     {
-        std::cerr << "Bad file descriptor for " << path << "\n";
+        lg2::error("Bad file descriptor for '{PATH}'", "PATH", path);
         return;
     }
     if (err || bytesRead == 0)
     {
         if (readingStateGood())
         {
-            std::cerr << name << " read failed\n";
+            lg2::error("'{NAME}' read failed", "NAME", name);
         }
         restartRead();
         return;
@@ -237,7 +239,7 @@
     }
     catch (const std::invalid_argument&)
     {
-        std::cerr << "Could not parse  input from " << path << "\n";
+        lg2::error("Could not parse input from '{PATH}'", "PATH", path);
         incrementError();
     }
 
diff --git a/src/psu/PSUSensorMain.cpp b/src/psu/PSUSensorMain.cpp
index d125470..a02ad17 100644
--- a/src/psu/PSUSensorMain.cpp
+++ b/src/psu/PSUSensorMain.cpp
@@ -31,6 +31,7 @@
 #include <boost/asio/steady_timer.hpp>
 #include <boost/container/flat_map.hpp>
 #include <boost/container/flat_set.hpp>
+#include <phosphor-logging/lg2.hpp>
 #include <sdbusplus/asio/connection.hpp>
 #include <sdbusplus/asio/object_server.hpp>
 #include <sdbusplus/bus.hpp>
@@ -50,7 +51,6 @@
 #include <filesystem>
 #include <fstream>
 #include <functional>
-#include <iostream>
 #include <iterator>
 #include <memory>
 #include <regex>
@@ -316,7 +316,7 @@
     findFiles(std::filesystem::path("/sys/class/hwmon"), "name", pmbusPaths);
     if (pmbusPaths.empty())
     {
-        std::cerr << "No PSU sensors in system\n";
+        lg2::error("No PSU sensors in system");
         return;
     }
 
@@ -329,7 +329,7 @@
         std::ifstream nameFile(pmbusPath);
         if (!nameFile.good())
         {
-            std::cerr << "Failure finding pmbus path " << pmbusPath << "\n";
+            lg2::error("Failure finding '{PATH}'", "PATH", pmbusPath);
             continue;
         }
 
@@ -341,8 +341,8 @@
         {
             // To avoid this error message, add your driver name to
             // the pmbusNames vector at the top of this file.
-            std::cerr << "Driver name " << pmbusName
-                      << " not found in sensor whitelist\n";
+            lg2::error("'{NAME}' not found in sensor whitelist", "NAME",
+                       pmbusName);
             continue;
         }
 
@@ -351,7 +351,7 @@
         auto ret = directories.insert(directory.string());
         if (!ret.second)
         {
-            std::cerr << "Duplicate path " << directory.string() << "\n";
+            lg2::error("Duplicate path: '{PATH}'", "PATH", directory);
             continue; // check if path has already been searched
         }
 
@@ -366,7 +366,8 @@
             std::regex_search(devicePath, match, i2cDevRegex);
             if (match.empty())
             {
-                std::cerr << "Found bad device path " << devicePath << "\n";
+                lg2::error("Found bad device path: '{PATH}'", "PATH",
+                           devicePath);
                 continue;
             }
             // Extract <bus>-<address>
@@ -408,8 +409,8 @@
             }
             if (baseConfig == nullptr)
             {
-                std::cerr << "error finding base configuration for "
-                          << deviceName << "\n";
+                lg2::error("error finding base configuration for '{NAME}'",
+                           "NAME", deviceName);
                 continue;
             }
 
@@ -419,7 +420,7 @@
             if (configBus == baseConfig->end() ||
                 configAddress == baseConfig->end())
             {
-                std::cerr << "error finding necessary entry in configuration\n";
+                lg2::error("error finding necessary entry in configuration");
                 continue;
             }
 
@@ -429,8 +430,7 @@
                 std::get_if<uint64_t>(&(configAddress->second));
             if (confBus == nullptr || confAddr == nullptr)
             {
-                std::cerr
-                    << "Cannot get bus or address, invalid configuration\n";
+                lg2::error("Cannot get bus or address, invalid configuration");
                 continue;
             }
 
@@ -438,9 +438,10 @@
             {
                 if constexpr (debug)
                 {
-                    std::cerr << "Configuration skipping " << *confBus << "-"
-                              << *confAddr << " because not " << bus << "-"
-                              << addr << "\n";
+                    lg2::error(
+                        "Configuration skipping '{CONFBUS}'-'{CONFADDR}' because not {BUS}-{ADDR}",
+                        "CONFBUS", *confBus, "CONFADDR", *confAddr, "BUS", bus,
+                        "ADDR", addr);
                 }
                 continue;
             }
@@ -448,7 +449,7 @@
             std::vector<thresholds::Threshold> confThresholds;
             if (!parseThresholdsFromConfig(*sensorData, confThresholds))
             {
-                std::cerr << "error populating total thresholds\n";
+                lg2::error("error populating total thresholds");
             }
             thresholdConfSize = confThresholds.size();
 
@@ -459,7 +460,7 @@
         {
             // To avoid this error message, add your export map entry,
             // from Entity Manager, to sensorTypes at the top of this file.
-            std::cerr << "failed to find match for " << deviceName << "\n";
+            lg2::error("failed to find match for '{NAME}'", "NAME", deviceName);
             continue;
         }
 
@@ -478,15 +479,15 @@
         auto findPSUName = baseConfig->find("Name");
         if (findPSUName == baseConfig->end())
         {
-            std::cerr << "could not determine configuration name for "
-                      << deviceName << "\n";
+            lg2::error("could not determine configuration name for '{NAME}'",
+                       "NAME", deviceName);
             continue;
         }
         const std::string* psuName =
             std::get_if<std::string>(&(findPSUName->second));
         if (psuName == nullptr)
         {
-            std::cerr << "Cannot find psu name, invalid configuration\n";
+            lg2::error("Cannot find psu name, invalid configuration");
             continue;
         }
 
@@ -537,7 +538,7 @@
         if (!findFiles(directory, devParamMap[devType].matchRegEx, sensorPaths,
                        0))
         {
-            std::cerr << "No PSU non-label sensor in PSU\n";
+            lg2::error("No PSU non-label sensor in PSU");
             continue;
         }
 
@@ -546,7 +547,7 @@
         {
             if constexpr (debug)
             {
-                std::cerr << "No max name in PSU \n";
+                lg2::error("No max name in PSU");
             }
         }
 
@@ -581,8 +582,8 @@
             }
             else
             {
-                std::cerr << "Could not extract the alpha prefix from "
-                          << sensorNameStr;
+                lg2::error("Could not extract the alpha prefix from '{NAME}'",
+                           "NAME", sensorNameStr);
                 continue;
             }
 
@@ -618,8 +619,9 @@
                 {
                     if constexpr (debug)
                     {
-                        std::cerr << "Input file " << sensorPath
-                                  << " has no corresponding label file\n";
+                        lg2::error(
+                            "Input file '{PATH}' has no corresponding label file",
+                            "PATH", sensorPath.string());
                     }
                     // hwmon *_input filename with number:
                     // temp1, temp2, temp3, ...
@@ -659,8 +661,8 @@
 
             if constexpr (debug)
             {
-                std::cerr << "Sensor type=\"" << sensorNameSubStr
-                          << "\" label=\"" << labelHead << "\"\n";
+                lg2::error("Sensor type: {NAME}, label: {LABEL}", "NAME",
+                           sensorNameSubStr, "LABEL", labelHead);
             }
 
             if (!findLabels.empty())
@@ -671,8 +673,9 @@
                 {
                     if constexpr (debug)
                     {
-                        std::cerr << "could not find " << labelHead
-                                  << " in the Labels list\n";
+                        lg2::error(
+                            "could not find '{LABEL}' in the Labels list",
+                            "LABEL", labelHead);
                     }
                     continue;
                 }
@@ -687,8 +690,9 @@
             {
                 if constexpr (debug)
                 {
-                    std::cerr << "Could not find matching default property for "
-                              << labelHead << "\n";
+                    lg2::error(
+                        "Could not find matching default property for '{LABEL}'",
+                        "LABEL", labelHead);
                 }
                 continue;
             }
@@ -719,7 +723,7 @@
                 }
                 catch (const std::invalid_argument&)
                 {
-                    std::cerr << "Unable to parse " << keyName << "\n";
+                    lg2::error("Unable to parse '{NAME}'", "NAME", keyName);
                     continue;
                 }
 
@@ -738,7 +742,7 @@
                 }
                 catch (const std::invalid_argument&)
                 {
-                    std::cerr << "Unable to parse " << keyScale << "\n";
+                    lg2::error("Unable to parse '{SCALE}'", "SCALE", keyScale);
                     continue;
                 }
 
@@ -749,7 +753,7 @@
                 }
                 else
                 {
-                    std::cerr << "Unable to accept " << keyScale << "\n";
+                    lg2::error("Unable to accept '{SCALE}'", "SCALE", keyScale);
                     continue;
                 }
             }
@@ -764,7 +768,7 @@
                 }
                 catch (const std::invalid_argument&)
                 {
-                    std::cerr << "Unable to parse " << keyMin << "\n";
+                    lg2::error("Unable to parse '{MIN}'", "MIN", keyMin);
                     continue;
                 }
             }
@@ -779,7 +783,7 @@
                 }
                 catch (const std::invalid_argument&)
                 {
-                    std::cerr << "Unable to parse " << keyMax << "\n";
+                    lg2::error("Unable to parse '{MAX}'", "MAX", keyMax);
                     continue;
                 }
             }
@@ -794,7 +798,8 @@
                 }
                 catch (const std::invalid_argument&)
                 {
-                    std::cerr << "Unable to parse " << keyOffset << "\n";
+                    lg2::error("Unable to parse '{OFFSET}'", "OFFSET",
+                               keyOffset);
                     continue;
                 }
             }
@@ -809,7 +814,7 @@
             }
             if (!(psuProperty.minReading < psuProperty.maxReading))
             {
-                std::cerr << "Min must be less than Max\n";
+                lg2::error("Min must be less than Max");
                 continue;
             }
 
@@ -844,8 +849,8 @@
 
                 if (psuNames.size() <= nameIndex)
                 {
-                    std::cerr << "Could not pair " << labelHead
-                              << " with a Name field\n";
+                    lg2::error("Could not pair '{LABEL}' with a Name field",
+                               "LABEL", labelHead);
                     continue;
                 }
 
@@ -853,9 +858,10 @@
 
                 if constexpr (debug)
                 {
-                    std::cerr << "Sensor label head " << labelHead
-                              << " paired with " << psuNameFromIndex
-                              << " at index " << nameIndex << "\n";
+                    lg2::error(
+                        "'{LABEL}' paired with '{NAME}' at index '{INDEX}'",
+                        "LABEL", labelHead, "NAME", psuNameFromIndex, "INDEX",
+                        nameIndex);
                 }
             }
 
@@ -890,8 +896,9 @@
 
                 if constexpr (debug)
                 {
-                    std::cerr << "Sensor scaling factor " << factor
-                              << " string " << strScaleFactor << "\n";
+                    lg2::error(
+                        "Sensor scaling factor '{FACTOR}' string '{SCALE_FACTOR}'",
+                        "FACTOR", factor, "SCALE_FACTOR", strScaleFactor);
                 }
             }
 
@@ -899,26 +906,27 @@
             if (!parseThresholdsFromConfig(*sensorData, sensorThresholds,
                                            &labelHead))
             {
-                std::cerr << "error populating thresholds for "
-                          << sensorNameSubStr << "\n";
+                lg2::error("error populating thresholds for '{NAME}'", "NAME",
+                           sensorNameSubStr);
             }
 
             auto findSensorUnit = sensorTable.find(sensorNameSubStr);
             if (findSensorUnit == sensorTable.end())
             {
-                std::cerr << sensorNameSubStr
-                          << " is not a recognized sensor type\n";
+                lg2::error("'{NAME}' is not a recognized sensor type", "NAME",
+                           sensorNameSubStr);
                 continue;
             }
 
             if constexpr (debug)
             {
-                std::cerr << "Sensor properties: Name \""
-                          << psuProperty.labelTypeName << "\" Scale "
-                          << psuProperty.sensorScaleFactor << " Min "
-                          << psuProperty.minReading << " Max "
-                          << psuProperty.maxReading << " Offset "
-                          << psuProperty.sensorOffset << "\n";
+                lg2::error("Sensor properties - Name: {NAME}, Scale: {SCALE}, "
+                           "Min: {MIN}, Max: {MAX}, Offset: {OFFSET}",
+                           "NAME", psuProperty.labelTypeName, "SCALE",
+                           psuProperty.sensorScaleFactor, "MIN",
+                           psuProperty.minReading, "MAX",
+                           psuProperty.maxReading, "OFFSET",
+                           psuProperty.sensorOffset);
             }
 
             std::string sensorName = psuProperty.labelTypeName;
@@ -928,7 +936,7 @@
                 {
                     // Allow selective disabling of an individual sensor,
                     // by customizing its name to an empty string.
-                    std::cerr << "Sensor disabled, empty string\n";
+                    lg2::error("Sensor disabled, empty string");
                     continue;
                 }
             }
@@ -948,9 +956,9 @@
 
             if constexpr (debug)
             {
-                std::cerr << "Sensor name \"" << sensorName << "\" path \""
-                          << sensorPathStr << "\" type \"" << sensorType
-                          << "\"\n";
+                lg2::error("Sensor name: {NAME}, path: {PATH}, type: {TYPE}",
+                           "NAME", sensorName, "PATH", sensorPathStr, "TYPE",
+                           sensorType);
             }
             // destruct existing one first if already created
 
@@ -977,8 +985,8 @@
                 ++numCreated;
                 if constexpr (debug)
                 {
-                    std::cerr
-                        << "Created " << numCreated << " sensors so far\n";
+                    lg2::error("Created '{NUM}' sensors so far", "NUM",
+                               numCreated);
                 }
             }
         }
@@ -997,7 +1005,7 @@
 
     if constexpr (debug)
     {
-        std::cerr << "Created total of " << numCreated << " sensors\n";
+        lg2::error("Created total of '{NUM}' sensors", "NUM", numCreated);
     }
 }
 
@@ -1020,8 +1028,7 @@
     }
     catch (sdbusplus::exception_t& e)
     {
-        std::cerr << "error getting inventory item subtree: " << e.what()
-                  << "\n";
+        lg2::error("error getting inventory item subtree: '{ERR}'", "ERR", e);
         return;
     }
 
@@ -1048,7 +1055,7 @@
         }
         catch (sdbusplus::exception_t& e)
         {
-            std::cerr << "Error in getting CPU presence: " << e.what() << "\n";
+            lg2::error("Error in getting CPU presence: '{ERR}'", "ERR", e);
             continue;
         }
 
@@ -1062,7 +1069,7 @@
             }
             catch (const std::exception& e)
             {
-                std::cerr << "Error converting CPU index, " << e.what() << '\n';
+                lg2::error("Error converting CPU index: '{ERR}'", "ERR", e);
                 continue;
             }
             cpuPresence[cpuIndex] = *present;
@@ -1186,7 +1193,7 @@
         [&](sdbusplus::message_t& message) {
             if (message.is_method_error())
             {
-                std::cerr << "callback method error\n";
+                lg2::error("callback method error");
                 return;
             }
             sensorsChanged->insert(message.get_path());
@@ -1198,7 +1205,7 @@
                 }
                 if (ec)
                 {
-                    std::cerr << "timer error\n";
+                    lg2::error("timer error");
                 }
                 createSensors(io, objectServer, systemBus, sensorsChanged,
                               false);
@@ -1224,7 +1231,7 @@
             }
             catch (const std::invalid_argument&)
             {
-                std::cerr << "Found invalid path " << path << "\n";
+                lg2::error("Found invalid path: '{PATH}'", "PATH", path);
                 return;
             }
 
@@ -1257,7 +1264,7 @@
                 }
                 if (ec)
                 {
-                    std::cerr << "timer error\n";
+                    lg2::error("timer error");
                     return;
                 }
                 createSensors(io, objectServer, systemBus, nullptr, false);