|
| 1 | +/* |
| 2 | + * Copyright (C) 2026 The Android Open Source Project |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +#include "cuttlefish/host/commands/cvd/cli/log_files.h" |
| 18 | + |
| 19 | +#include <chrono> |
| 20 | +#include <iomanip> |
| 21 | +#include <iostream> |
| 22 | +#include <sstream> |
| 23 | +#include <string> |
| 24 | +#include <vector> |
| 25 | + |
| 26 | +#include "absl/strings/str_cat.h" |
| 27 | + |
| 28 | +#include "cuttlefish/common/libs/utils/files.h" |
| 29 | +#include "cuttlefish/host/commands/cvd/utils/common.h" |
| 30 | + |
| 31 | +namespace cuttlefish { |
| 32 | + |
| 33 | +std::optional<std::string> GetLogFile() { |
| 34 | + std::string log_dir = PerUserDir() + "/logs"; |
| 35 | + if (!EnsureDirectoryExists(log_dir, 0777).ok()) { |
| 36 | + std::cerr << "Failed to create log directory: " << log_dir |
| 37 | + << ". Logging to file disabled." << std::endl; |
| 38 | + return std::nullopt; |
| 39 | + } |
| 40 | + |
| 41 | + std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); |
| 42 | + std::time_t now_time_t = std::chrono::system_clock::to_time_t(now); |
| 43 | + std::chrono::milliseconds now_ms = |
| 44 | + std::chrono::duration_cast<std::chrono::milliseconds>( |
| 45 | + now.time_since_epoch()) % |
| 46 | + 1000; |
| 47 | + |
| 48 | + std::tm tm_now; |
| 49 | + localtime_r(&now_time_t, &tm_now); |
| 50 | + |
| 51 | + std::stringstream ss; |
| 52 | + ss << std::put_time(&tm_now, "%Y%m%d_%H%M%S") << "." << std::setfill('0') |
| 53 | + << std::setw(3) << now_ms.count(); |
| 54 | + return absl::StrCat(log_dir, "/cvd_", ss.str(), ".log"); |
| 55 | +} |
| 56 | + |
| 57 | +} // namespace cuttlefish |
0 commit comments