Append a diagnostic line to a file in C++

A small diagnostic writer can use std::ofstream in append mode. A function keeps stream ownership and error handling visible and avoids a macro's surprising argument evaluation or statement expansion.

This example writes to a caller-selected path in the current working directory. It is intentionally a small single-process utility, not a complete concurrent logging subsystem.

Write a complete line

Save as log-demo.cpp. It requires a C++17-capable compiler.

C++
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string_view>

void append_line(const char* path, std::string_view message) {
    std::ofstream stream(path, std::ios::app);
    if (!stream) throw std::runtime_error("Cannot open diagnostic file");
    stream << message << '\n';
    stream.flush();
    if (!stream) throw std::runtime_error("Cannot write diagnostic file");
}

int main() {
    try {
        append_line("diagnostic.log", "Started");
        std::cout << "Appended one line\n";
    } catch (const std::exception& error) {
        std::cerr << error.what() << '\n';
        return 1;
    }
}

With GCC or Clang, compile with c++ -std=c++17 log-demo.cpp -o log-demo and run the resulting executable. In an MSVC developer terminal, use cl /std:c++17 /EHsc log-demo.cpp and run log-demo.exe.

Expect Appended one line and a new Started line in diagnostic.log. Running again appends another line.

Decide the logging contract

The stream closes when it leaves scope, including exception paths. Explicit flushing lets this example detect a write failure before returning. It does not guarantee the bytes have reached durable physical storage.

Several threads or processes writing the same file need a coordinated design. Use a dedicated writer or an established logging library for concurrent writes, rotation and structured records. To make a call debug-only, guard that call with the project's explicit build policy. Do not silently discard operational failures in release builds.

Official references

basic_ofstream Class
Learn more about: basic_ofstream Class
https://learn.microsoft.com/en-us/cpp/standard-library/basic-ofstream-class?view=msvc-170
basic_ofstream

Author: Herman Schoenfeld