Skip to content

Commit

Permalink
feat: log api error (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
xsigoking committed Apr 11, 2024
1 parent 523e39f commit 098ee27
Show file tree
Hide file tree
Showing 3 changed files with 109 additions and 3 deletions.
91 changes: 91 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@ keywords = ["chatgpt", "api"]
anyhow = "1.0.81"
bytes = "1.5"
chrono = "0.4.37"
env_logger = "0.11.3"
futures-util = "0.3.30"
http = "1.1.0"
http-body-util = "0.1"
hyper = { version = "1.0", features = ["full"] }
hyper-util = { version = "0.1", features = ["server-auto", "client-legacy"] }
log = "0.4.21"
rand = "0.8.5"
reqwest-eventsource = "0.6.0"
serde = { version = "1.0", features = ["derive"] }
Expand Down
19 changes: 16 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
#[macro_use]
extern crate log;

use anyhow::{anyhow, bail, Result};
use bytes::Bytes;
use chrono::Utc;
Expand Down Expand Up @@ -25,6 +28,8 @@ const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);

#[tokio::main]
async fn main() -> Result<()> {
init_logger();

let port = if let Ok(port) = env::var("PORT") {
port.parse::<u16>()
.map_err(|_| anyhow!("Invalid environment variable $PORT"))?
Expand All @@ -44,7 +49,7 @@ async fn main() -> Result<()> {
client: client_builder.build()?,
});
let stop_server = server.run(listener).await?;
print!(
println!(
r#"Access the API server at: http://0.0.0.0:{port}/v1/chat/completions
Environment Variables:
Expand All @@ -60,6 +65,14 @@ Please contact us at https://github.com/xsigoking/chatgpt-free-api if you encoun
Ok(())
}

fn init_logger() {
env_logger::builder()
.parse_env(env_logger::Env::new().filter_or("RUST_LOG", "info"))
.format_target(false)
.format_module_path(false)
.init();
}

type AppResponse = Response<BoxBody<Bytes, Infallible>>;

struct Server {
Expand Down Expand Up @@ -186,7 +199,7 @@ impl Server {
"websocket_request_id": random_id(),
});

// println!("req body: {req_body}");
debug!("req body: {req_body}");

let mut es = self
.client
Expand Down Expand Up @@ -260,7 +273,6 @@ impl Server {
let created = Utc::now().timestamp();

let first_event = rx.recv().await;
// println!("first event: {first_event:?}");

if let Some(ResEvent::First(Some(err))) = first_event {
bail!("{err}");
Expand Down Expand Up @@ -469,6 +481,7 @@ fn create_bytes_body(id: &str, created: i64, content: &str) -> Bytes {
}

fn create_error_response<T: std::fmt::Display>(err: T) -> AppResponse {
error!("api error: {err}");
let data = json!({
"status": false,
"error": {
Expand Down

0 comments on commit 098ee27

Please sign in to comment.