John Harrison 8d57635c59
[lldb-dap] Improving logging support and formatting. (#170731)
Adjusting logs in a few ways:

* The `DAP_LOG` and `DAP_LOG_ERROR` macros now include the file/line of
the log statement.
* Added support for creating a log with a prefix. This simplifies how we
create logs for the `lldb_dap::DAP` instance and `lldb_dap::Transport`
instance, allowing us to not have to pass the client name around as
much.
* Updated logging usage to take the `lldb_dap::Log` as a reference but
it now defaults to `llvm::raw_null_stream` if not configured. This
ensures more uniform access to the logger, even if its not written
anywhere.

The logs now look like:

```
1764896564.038788080 (stdio) --> {"command":"initialize","arguments":{...},"type":"request","seq":1}
1764896564.039064884 DAP.cpp:1007 (stdio) queued (command=initialize seq=1)
1764896564.039768934 (stdio) <-- {"body":{...},"command":"initialize","request_seq":1,"seq":1,"success":true,"type":"response"}
```
2025-12-05 15:43:40 -08:00

36 lines
1.1 KiB
C++

//===-- DAPLog.cpp --------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "DAPLog.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Chrono.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <chrono>
#include <mutex>
using namespace llvm;
namespace lldb_dap {
void Log::Emit(StringRef message) { Emit(message, "", 0); }
void Log::Emit(StringRef message, StringRef file, size_t line) {
std::lock_guard<Log::Mutex> lock(m_mutex);
const llvm::sys::TimePoint<> time = std::chrono::system_clock::now();
m_stream << formatv("[{0:%H:%M:%S.%L}]", time) << " ";
if (!file.empty())
m_stream << sys::path::filename(file) << ":" << line << " ";
if (!m_prefix.empty())
m_stream << m_prefix;
m_stream << message << "\n";
m_stream.flush();
}
} // namespace lldb_dap