Skip to content

Commit fc88f61

Browse files
committed
log: add Rust log init for C++
- Add lib for log init when Rust lib is used by C++. - Add example.
1 parent b3210fd commit fc88f61

File tree

8 files changed

+470
-0
lines changed

8 files changed

+470
-0
lines changed

.clang-format

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
BasedOnStyle: Google
2+
AccessModifierOffset: -2
3+
AllowAllParametersOfDeclarationOnNextLine: false
4+
AllowShortBlocksOnASingleLine: Empty
5+
AllowShortCaseLabelsOnASingleLine: false
6+
AllowShortEnumsOnASingleLine: false
7+
# Empty is required in AllowShortFunctionsOnASingleLine over Inline because Inline contradicts with AUTOSAR rule A7-1-7
8+
# Such rule is no longer existing in MISRA C++:2023, once we are fully migrated to MISRA C++:2023, switching to Inline
9+
# could be reconsidered
10+
AllowShortFunctionsOnASingleLine: Empty
11+
AllowShortIfStatementsOnASingleLine: Never
12+
AllowShortLambdasOnASingleLine: Empty
13+
AllowShortLoopsOnASingleLine: false
14+
BinPackArguments: false
15+
BinPackParameters: false
16+
BraceWrapping:
17+
AfterCaseLabel: true
18+
AfterClass: true
19+
AfterControlStatement: Always
20+
AfterEnum: true
21+
AfterFunction: true
22+
AfterNamespace: true
23+
AfterObjCDeclaration: true
24+
AfterStruct: true
25+
AfterUnion: true
26+
BeforeCatch: true
27+
BeforeElse: true
28+
IndentBraces: false
29+
BreakBeforeBraces: Custom
30+
ColumnLimit: 120
31+
DerivePointerAlignment: false
32+
IncludeBlocks: Preserve
33+
IncludeCategories:
34+
- Regex: '^(<|")(assert|complex|ctype|errno|fenv|float|inttypes|iso646|limits|locale|math|setjmp|signal|stdalign|stdargh|stdatomic|stdbool|stddef|stdint|stdio|stdlib|stdnoreturn|string|tgmath|threads|time|uchar|wchar|wctype)\.h(>|")$'
35+
Priority: 2
36+
- Regex: '^(<|")(cstdlib|csignal|csetjmp|cstdarg|typeinfo|typeindex|type_traits|bitset|functional|utility|ctime|chrono|cstddef|initializer_list|tuple|any|optional|variant|new|memory|scoped_allocator|memory_resource|climits|cfloat|cstdint|cinttypes|limits|exception|stdexcept|cassert|system_error|cerrno|cctype|cwctype|cstring|cwchar|cuchar|string|string_view|array|vector|deque|list|forward_list|set|map|unordered_set|unordered_map|stack|queue|algorithm|execution|teratorslibrary|iterator|cmath|complex|valarray|random|numeric|ratio|cfenv|iosfwd|ios|istream|ostream|iostream|fstream|sstream|strstream|iomanip|streambuf|cstdio|locale|clocale|codecvt|regex|atomic|thread|mutex|shared_mutex|future|condition_variable|filesystem|ciso646|ccomplex|ctgmath|cstdalign|cstdbool)(>|")$'
37+
Priority: 3
38+
- Regex: '^(<|").*(>|")$'
39+
Priority: 1
40+
IndentWidth: 4
41+
InsertNewlineAtEOF: true
42+
KeepEmptyLinesAtTheStartOfBlocks: true
43+
QualifierAlignment: Left
44+
CommentPragmas: '^.*A2Lfactory:'
45+
---
46+
# Make sure language specific settings are below the generic settings to be compatible to all languages.
47+
Language: Cpp
48+
Standard: c++17

examples/log_cpp_init/BUILD

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# *******************************************************************************
2+
# Copyright (c) 2025 Contributors to the Eclipse Foundation
3+
#
4+
# See the NOTICE file(s) distributed with this work for additional
5+
# information regarding copyright ownership.
6+
#
7+
# This program and the accompanying materials are made available under the
8+
# terms of the Apache License Version 2.0 which is available at
9+
# https://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# SPDX-License-Identifier: Apache-2.0
12+
# *******************************************************************************
13+
14+
load("@rules_cc//cc:defs.bzl", "cc_binary")
15+
load("@rules_rust//rust:defs.bzl", "rust_static_library")
16+
17+
rust_static_library(
18+
name = "example_lib_rs",
19+
srcs = ["src/example_lib.rs"],
20+
edition = "2021",
21+
visibility = ["//visibility:private"],
22+
deps = [
23+
"//src/log/score_log",
24+
"//src/log/stdout_logger",
25+
],
26+
)
27+
28+
cc_binary(
29+
name = "log_cpp_init",
30+
srcs = ["src/main.cpp"],
31+
linkopts = ["-lpthread"],
32+
visibility = ["//visibility:public"],
33+
deps = [
34+
":example_lib_rs",
35+
"//src/log/stdout_logger_init",
36+
],
37+
)
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
//
2+
// Copyright (c) 2025 Contributors to the Eclipse Foundation
3+
//
4+
// See the NOTICE file(s) distributed with this work for additional
5+
// information regarding copyright ownership.
6+
//
7+
// This program and the accompanying materials are made available under the
8+
// terms of the Apache License Version 2.0 which is available at
9+
// <https://www.apache.org/licenses/LICENSE-2.0>
10+
//
11+
// SPDX-License-Identifier: Apache-2.0
12+
//
13+
14+
//! Module contains functions printing example logs.
15+
//! Based on `//score/mw/log/rust/score_log_bridge:example`.
16+
17+
use score_log::{debug, error, fatal, info, trace, warn, Log};
18+
use stdout_logger::StdoutLoggerBuilder;
19+
20+
/// Show example logs using global logger.
21+
#[no_mangle]
22+
extern "C" fn show_logs_global_logger() {
23+
// Regular log usage.
24+
trace!("This is a trace log - hidden");
25+
debug!("This is a debug log - hidden");
26+
info!("This is an info log");
27+
warn!("This is a warn log");
28+
error!("This is an error log");
29+
fatal!("This is a fatal log");
30+
31+
// Log with modified context.
32+
trace!(context: "EX1", "This is a trace log - hidden");
33+
debug!(context: "EX1", "This is a debug log - hidden");
34+
info!(context: "EX1", "This is an info log");
35+
warn!(context: "EX1", "This is a warn log");
36+
error!(context: "EX1", "This is an error log");
37+
fatal!(context: "EX1", "This is a fatal log");
38+
39+
// Log with numeric values.
40+
let x1 = 123.4;
41+
let x2 = 111;
42+
let x3 = true;
43+
let x4 = -0x3Fi8;
44+
error!(
45+
"This is an error log with numeric values: {} {} {} {:x}",
46+
x1, x2, x3, x4,
47+
);
48+
}
49+
50+
/// Show example logs using function-logger logger instance.
51+
#[no_mangle]
52+
extern "C" fn show_logs_local_logger() {
53+
// Use logger instance with modified context.
54+
let logger = StdoutLoggerBuilder::new()
55+
.context("ALFA")
56+
.show_module(false)
57+
.show_file(true)
58+
.show_line(false)
59+
.build();
60+
61+
// Log with provided logger.
62+
trace!(
63+
logger: logger,
64+
"This is a trace log - hidden"
65+
);
66+
debug!(logger: logger, "This is a debug log - hidden");
67+
info!(logger: logger, "This is an info log");
68+
warn!(logger: logger, "This is a warn log");
69+
error!(logger: logger, "This is an error log");
70+
fatal!(logger: logger, "This is an fatal log");
71+
72+
// Log with provided logger and modified context.
73+
trace!(logger: logger, context: "EX2", "This is a trace log - hidden");
74+
debug!(logger: logger, context: "EX2", "This is a debug log - hidden");
75+
info!(logger: logger, context: "EX2", "This is an info log");
76+
warn!(logger: logger, context: "EX2", "This is a warn log");
77+
error!(logger: logger, context: "EX2", "This is an error log");
78+
fatal!(logger: logger, context: "EX2", "This is an fatal log");
79+
}

examples/log_cpp_init/src/main.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/********************************************************************************
2+
* Copyright (c) 2025 Contributors to the Eclipse Foundation
3+
*
4+
* See the NOTICE file(s) distributed with this work for additional
5+
* information regarding copyright ownership.
6+
*
7+
* This program and the accompanying materials are made available under the
8+
* terms of the Apache License Version 2.0 which is available at
9+
* https://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* SPDX-License-Identifier: Apache-2.0
12+
********************************************************************************/
13+
14+
#include "score/mw/log/rust/stdout_logger_init.hpp"
15+
16+
extern "C" {
17+
void show_logs_global_logger();
18+
void show_logs_local_logger();
19+
}
20+
21+
int main()
22+
{
23+
using namespace score::mw::log::rust;
24+
25+
StdoutLoggerBuilder builder;
26+
builder.Context("ABCD").ShowModule(true).ShowFile(true).ShowLine(true).SetAsDefaultLogger();
27+
28+
show_logs_global_logger();
29+
show_logs_local_logger();
30+
31+
return 0;
32+
}

src/log/stdout_logger_init/BUILD

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# *******************************************************************************
2+
# Copyright (c) 2025 Contributors to the Eclipse Foundation
3+
#
4+
# See the NOTICE file(s) distributed with this work for additional
5+
# information regarding copyright ownership.
6+
#
7+
# This program and the accompanying materials are made available under the
8+
# terms of the Apache License Version 2.0 which is available at
9+
# https://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# SPDX-License-Identifier: Apache-2.0
12+
# *******************************************************************************
13+
14+
load("@rules_cc//cc:defs.bzl", "cc_library")
15+
load("@rules_rust//rust:defs.bzl", "rust_static_library")
16+
17+
rust_static_library(
18+
name = "ffi",
19+
srcs = ["ffi.rs"],
20+
edition = "2021",
21+
visibility = ["//visibility:private"],
22+
deps = [
23+
"//src/log/score_log",
24+
"//src/log/stdout_logger",
25+
],
26+
)
27+
28+
cc_library(
29+
name = "stdout_logger_init",
30+
srcs = ["stdout_logger_init.cpp"],
31+
hdrs = ["stdout_logger_init.hpp"],
32+
include_prefix = "score/mw/log/rust",
33+
visibility = ["//visibility:public"],
34+
deps = [
35+
":ffi",
36+
],
37+
)

src/log/stdout_logger_init/ffi.rs

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
//
2+
// Copyright (c) 2025 Contributors to the Eclipse Foundation
3+
//
4+
// See the NOTICE file(s) distributed with this work for additional
5+
// information regarding copyright ownership.
6+
//
7+
// This program and the accompanying materials are made available under the
8+
// terms of the Apache License Version 2.0 which is available at
9+
// <https://www.apache.org/licenses/LICENSE-2.0>
10+
//
11+
// SPDX-License-Identifier: Apache-2.0
12+
//
13+
14+
use core::ffi::c_char;
15+
use core::slice::from_raw_parts;
16+
use stdout_logger::StdoutLoggerBuilder;
17+
18+
/// Represents severity of a log message.
19+
#[derive(Clone, Copy)]
20+
#[repr(u8)]
21+
#[allow(dead_code)]
22+
enum LogLevel {
23+
Off = 0x00,
24+
Fatal = 0x01,
25+
Error = 0x02,
26+
Warn = 0x03,
27+
Info = 0x04,
28+
Debug = 0x05,
29+
Verbose = 0x06,
30+
}
31+
32+
impl From<LogLevel> for score_log::LevelFilter {
33+
fn from(level: LogLevel) -> score_log::LevelFilter {
34+
match level {
35+
LogLevel::Off => score_log::LevelFilter::Off,
36+
LogLevel::Fatal => score_log::LevelFilter::Fatal,
37+
LogLevel::Error => score_log::LevelFilter::Error,
38+
LogLevel::Warn => score_log::LevelFilter::Warn,
39+
LogLevel::Info => score_log::LevelFilter::Info,
40+
LogLevel::Debug => score_log::LevelFilter::Debug,
41+
LogLevel::Verbose => score_log::LevelFilter::Trace,
42+
}
43+
}
44+
}
45+
46+
#[no_mangle]
47+
extern "C" fn set_default_logger(
48+
context_ptr: *const c_char,
49+
context_size: usize,
50+
show_module: *const bool,
51+
show_file: *const bool,
52+
show_line: *const bool,
53+
log_level: *const LogLevel,
54+
) {
55+
let mut builder = StdoutLoggerBuilder::new();
56+
57+
// Set parameters if non-null (option-like).
58+
if !context_ptr.is_null() {
59+
let context = unsafe {
60+
let slice = from_raw_parts(context_ptr.cast(), context_size);
61+
str::from_utf8_unchecked(slice)
62+
};
63+
builder = builder.context(context);
64+
}
65+
66+
if !show_module.is_null() {
67+
builder = builder.show_module(unsafe { *show_module });
68+
}
69+
70+
if !show_file.is_null() {
71+
builder = builder.show_file(unsafe { *show_file });
72+
}
73+
74+
if !show_line.is_null() {
75+
builder = builder.show_line(unsafe { *show_line });
76+
}
77+
78+
if !log_level.is_null() {
79+
builder = builder.log_level(unsafe { (*log_level).into() });
80+
}
81+
82+
builder.set_as_default_logger();
83+
}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/********************************************************************************
2+
* Copyright (c) 2025 Contributors to the Eclipse Foundation
3+
*
4+
* See the NOTICE file(s) distributed with this work for additional
5+
* information regarding copyright ownership.
6+
*
7+
* This program and the accompanying materials are made available under the
8+
* terms of the Apache License Version 2.0 which is available at
9+
* https://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* SPDX-License-Identifier: Apache-2.0
12+
********************************************************************************/
13+
14+
#include "stdout_logger_init.hpp"
15+
16+
extern "C" void set_default_logger(const char* context_ptr,
17+
size_t context_size,
18+
const bool* show_module,
19+
const bool* show_file,
20+
const bool* show_line,
21+
const score::mw::log::rust::LogLevel* log_level);
22+
23+
namespace score::mw::log::rust
24+
{
25+
26+
StdoutLoggerBuilder& StdoutLoggerBuilder::Context(const std::string& context) noexcept
27+
{
28+
context_ = context;
29+
return *this;
30+
}
31+
32+
StdoutLoggerBuilder& StdoutLoggerBuilder::ShowModule(bool show_module) noexcept
33+
{
34+
show_module_ = show_module;
35+
return *this;
36+
}
37+
38+
StdoutLoggerBuilder& StdoutLoggerBuilder::ShowFile(bool show_file) noexcept
39+
{
40+
show_file_ = show_file;
41+
return *this;
42+
}
43+
44+
StdoutLoggerBuilder& StdoutLoggerBuilder::ShowLine(bool show_line) noexcept
45+
{
46+
show_line_ = show_line;
47+
return *this;
48+
}
49+
50+
StdoutLoggerBuilder& StdoutLoggerBuilder::LogLevel(score::mw::log::rust::LogLevel log_level) noexcept
51+
{
52+
log_level_ = log_level;
53+
return *this;
54+
}
55+
56+
void StdoutLoggerBuilder::SetAsDefaultLogger() noexcept
57+
{
58+
const char* context_ptr{nullptr};
59+
size_t context_size{0};
60+
if (context_)
61+
{
62+
auto value{context_.value()};
63+
context_ptr = value.c_str();
64+
context_size = value.size();
65+
}
66+
67+
const bool* show_module{show_module_ ? &show_module_.value() : nullptr};
68+
const bool* show_file{show_file_ ? &show_file_.value() : nullptr};
69+
const bool* show_line{show_line_ ? &show_line_.value() : nullptr};
70+
const score::mw::log::rust::LogLevel* log_level{log_level_ ? &log_level_.value() : nullptr};
71+
72+
set_default_logger(context_ptr, context_size, show_module, show_file, show_line, log_level);
73+
}
74+
75+
} // namespace score::mw::log::rust

0 commit comments

Comments
 (0)