bool FileLogger::start()

in source/logging/FileLogger.cpp [20:93]


bool FileLogger::start(const PlainConfig &config)
{
    setLogLevel(config.logConfig.deviceClientlogLevel);
    if (!config.logConfig.deviceClientLogFile.empty())
    {
        logFile = config.logConfig.deviceClientLogFile;
    }

    struct stat info;
    string logFileDir = FileUtils::ExtractParentDirectory(logFile);
    if (stat(logFileDir.c_str(), &info) != 0)
    {
        cout << LOGGER_TAG << ": Cannot access " << logFileDir << "to write logs, attempting to create log directory"
             << endl;
        FileUtils::Mkdirs(logFileDir);
        if (stat(logFileDir.c_str(), &info) != 0)
        {
            cout << LOGGER_TAG << ": Failed to create log directories necessary for file-based logging" << endl;
            return false;
        }
        else
        {
            cout << LOGGER_TAG << ": Successfully created log directory! Now logging to " << logFile << endl;
        }
    }
    else if (info.st_mode & S_IFDIR)
    {
        // Log directory already exists, nothing to do here
    }
    else
    {
        cout << LOGGER_TAG << ": Unknown condition encountered while trying to create log directory" << endl;
        return false;
    }

    // Now we need to establish/verify permissions for the log directory and file
    if (Permissions::LOG_DIR != FileUtils::GetFilePermissions(logFileDir))
    {
        chmod(logFileDir.c_str(), S_IRWXU | S_IRGRP | S_IROTH | S_IXOTH);
        if (Permissions::LOG_DIR != FileUtils::GetFilePermissions(logFileDir))
        {
            cout << LOGGER_TAG
                 << FormatMessage(
                        "Failed to set appropriate permissions for log file directory %s, permissions should be set to "
                        "%d",
                        logFileDir.c_str(),
                        Permissions::LOG_DIR);
        }
    }

    outputStream = unique_ptr<ofstream>(new ofstream(logFile, std::fstream::app));
    if (!outputStream->fail())
    {
        if (Permissions::LOG_FILE != FileUtils::GetFilePermissions(logFile))
        {
            chmod(logFile.c_str(), S_IRUSR | S_IWUSR);
            if (Permissions::LOG_FILE != FileUtils::GetFilePermissions(logFile))
            {
                cout << LOGGER_TAG
                     << FormatMessage(
                            "Failed to set appropriate permissions for log file %s, permissions should be set to %d",
                            logFile.c_str(),
                            Permissions::LOG_FILE);
            }
        }

        thread log_thread(&FileLogger::run, this);
        log_thread.detach();
        return true;
    }

    cout << LOGGER_TAG << FormatMessage(": Failed to open %s for logging", logFile.c_str()) << endl;
    return false;
}