tracing_example/
tracing_example.rs1use tushare_api::{TushareClient, TushareRequest, Api, LogLevel, LogConfig};
7use std::collections::HashMap;
8
9#[tokio::main]
10async fn main() -> Result<(), Box<dyn std::error::Error>> {
11 println!("=== Tushare API Tracing Integration Example ===");
12
13 #[cfg(all(feature = "tracing", feature = "tracing-log"))]
15 {
16 println!("\n--- Method 1: Using tracing-log bridge ---");
17 use tracing_subscriber;
18 use tracing_log::LogTracer;
19
20 LogTracer::init()?;
22
23 tracing_subscriber::fmt()
25 .with_env_filter("debug")
26 .with_target(false)
27 .with_thread_ids(true)
28 .with_level(true)
29 .with_max_level(tracing::Level::DEBUG)
30 .init();
31 }
32
33 #[cfg(feature = "tracing")]
35 {
36 println!("\n--- Method 2: Using native tracing feature ---");
37 println!("库和用户程序都使用 tracing\n");
38
39 tracing_subscriber::fmt()
41 .with_max_level(tracing::Level::DEBUG)
42 .init();
43 }
44
45 println!("初始化 Tushare 客户端...");
46
47 let client = TushareClient::builder()
48 .with_token("demo_token_for_testing")
49 .with_log_level(LogLevel::Debug)
50 .log_requests(true)
51 .log_responses(false)
52 .log_performance(true)
53 .build()?;
54
55 println!("创建测试请求...");
56
57 let mut params = HashMap::new();
58 params.insert("list_status".to_string(), "L".to_string());
59
60 let request = TushareRequest {
61 api_name: Api::StockBasic,
62 params,
63 fields: vec!["ts_code".to_string(), "name".to_string()],
64 };
65
66 println!("发送 API 请求(注意观察日志输出)...");
67
68 match client.call_api(&request).await {
70 Ok(_response) => {
71 println!("✅ API 调用成功(实际会因为 token 无效而失败,但能看到日志)");
72 }
73 Err(e) => {
74 println!("❌ API 调用失败(预期行为): {}", e);
75 }
76 }
77
78 #[cfg(not(feature = "tracing"))]
79 {
80 println!("\n--- Tracing feature not enabled ---");
81 println!("To enable tracing support, compile with: cargo build --features tracing");
82 println!("Or add tracing-log bridge support with: cargo build --features tracing-log");
83 }
84
85 println!("\n=== 总结 ===");
86 #[cfg(feature = "tracing")]
87 println!("✅ 使用了原生 tracing 支持,日志输出更加结构化");
88
89 #[cfg(not(feature = "tracing"))]
90 println!("✅ 使用了 tracing-log 桥接,成功捕获了库的 log 输出");
91
92 Ok(())
93}