From 175ba70e8cf725f54fa415a33db7aaf62df0aed6 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Fri, 11 Jul 2025 12:37:10 +0200 Subject: [PATCH 01/31] [skip ci] Remove rabbit_log and switch to LOG_ macros --- deps/oauth2_client/src/oauth2_client.erl | 29 +++-- deps/rabbit/include/rabbit_amqp.hrl | 2 +- deps/rabbit/src/code_server_cache.erl | 4 +- deps/rabbit/src/file_handle_cache.erl | 12 +- deps/rabbit/src/mc_compat.erl | 3 +- deps/rabbit/src/mirrored_supervisor.erl | 28 ++-- deps/rabbit/src/rabbit.erl | 4 +- deps/rabbit/src/rabbit_access_control.erl | 11 +- deps/rabbit/src/rabbit_alarm.erl | 18 +-- deps/rabbit/src/rabbit_amqp_filter_sql.erl | 47 +++---- deps/rabbit/src/rabbit_amqp_management.erl | 3 +- deps/rabbit/src/rabbit_amqqueue.erl | 29 +++-- deps/rabbit/src/rabbit_amqqueue_process.erl | 5 +- deps/rabbit/src/rabbit_amqqueue_sup_sup.erl | 5 +- .../src/rabbit_auth_backend_internal.erl | 91 ++++++------- deps/rabbit/src/rabbit_autoheal.erl | 47 +++---- deps/rabbit/src/rabbit_binding.erl | 3 +- deps/rabbit/src/rabbit_boot_steps.erl | 6 +- deps/rabbit/src/rabbit_channel.erl | 12 +- deps/rabbit/src/rabbit_channel_tracking.erl | 5 +- deps/rabbit/src/rabbit_classic_queue.erl | 9 +- .../src/rabbit_classic_queue_index_v2.erl | 13 +- .../src/rabbit_classic_queue_store_v2.erl | 5 +- .../rabbit/src/rabbit_connection_tracking.erl | 9 +- deps/rabbit/src/rabbit_db_cluster.erl | 2 +- deps/rabbit/src/rabbit_db_msup.erl | 9 +- deps/rabbit/src/rabbit_db_queue.erl | 3 +- deps/rabbit/src/rabbit_db_vhost.erl | 11 +- deps/rabbit/src/rabbit_db_vhost_defaults.erl | 9 +- deps/rabbit/src/rabbit_dead_letter.erl | 3 +- deps/rabbit/src/rabbit_definitions.erl | 71 +++++----- .../rabbit/src/rabbit_definitions_hashing.erl | 3 +- .../src/rabbit_definitions_import_https.erl | 29 +++-- ...it_definitions_import_local_filesystem.erl | 27 ++-- deps/rabbit/src/rabbit_disk_monitor.erl | 35 ++--- deps/rabbit/src/rabbit_epmd_monitor.erl | 13 +- deps/rabbit/src/rabbit_exchange.erl | 5 +- deps/rabbit/src/rabbit_fifo.erl | 9 +- deps/rabbit/src/rabbit_fifo_client.erl | 17 ++- deps/rabbit/src/rabbit_fifo_dlx.erl | 11 +- deps/rabbit/src/rabbit_fifo_dlx_client.erl | 9 +- deps/rabbit/src/rabbit_fifo_dlx_worker.erl | 23 ++-- deps/rabbit/src/rabbit_fifo_v0.erl | 3 +- deps/rabbit/src/rabbit_fifo_v1.erl | 7 +- deps/rabbit/src/rabbit_fifo_v3.erl | 7 +- deps/rabbit/src/rabbit_health_check.erl | 5 +- deps/rabbit/src/rabbit_maintenance.erl | 35 ++--- deps/rabbit/src/rabbit_mnesia.erl | 35 ++--- deps/rabbit/src/rabbit_msg_store.erl | 37 +++--- deps/rabbit/src/rabbit_networking.erl | 21 +-- deps/rabbit/src/rabbit_node_monitor.erl | 39 +++--- deps/rabbit/src/rabbit_nodes.erl | 4 +- .../rabbit_peer_discovery_classic_config.erl | 9 +- deps/rabbit/src/rabbit_peer_discovery_dns.erl | 9 +- deps/rabbit/src/rabbit_plugins.erl | 25 ++-- deps/rabbit/src/rabbit_policy.erl | 3 +- deps/rabbit/src/rabbit_priority_queue.erl | 3 +- deps/rabbit/src/rabbit_queue_index.erl | 5 +- deps/rabbit/src/rabbit_queue_type.erl | 3 +- deps/rabbit/src/rabbit_quorum_queue.erl | 117 ++++++++--------- deps/rabbit/src/rabbit_reader.erl | 5 +- deps/rabbit/src/rabbit_recovery_terms.erl | 13 +- deps/rabbit/src/rabbit_runtime_parameters.erl | 7 +- deps/rabbit/src/rabbit_ssl.erl | 5 +- deps/rabbit/src/rabbit_stream_coordinator.erl | 109 ++++++++-------- deps/rabbit/src/rabbit_stream_queue.erl | 29 +++-- .../src/rabbit_stream_sac_coordinator.erl | 7 +- .../src/rabbit_stream_sac_coordinator_v4.erl | 5 +- deps/rabbit/src/rabbit_sysmon_handler.erl | 11 +- deps/rabbit/src/rabbit_table.erl | 11 +- deps/rabbit/src/rabbit_trace.erl | 13 +- deps/rabbit/src/rabbit_tracking.erl | 7 +- .../rabbit/src/rabbit_upgrade_preparation.erl | 7 +- deps/rabbit/src/rabbit_variable_queue.erl | 11 +- deps/rabbit/src/rabbit_vhost.erl | 63 ++++----- deps/rabbit/src/rabbit_vhost_msg_store.erl | 5 +- deps/rabbit/src/rabbit_vhost_process.erl | 9 +- deps/rabbit/src/rabbit_vhost_sup_sup.erl | 15 ++- deps/rabbit/src/rabbit_vhosts.erl | 17 ++- deps/rabbit/src/vm_memory_monitor.erl | 29 +++-- .../rabbit/test/unit_log_management_SUITE.erl | 3 +- deps/rabbit_common/codegen.py | 2 +- deps/rabbit_common/src/app_utils.erl | 5 +- .../src/rabbit_amqp_connection.erl | 7 +- .../src/rabbit_binary_generator.erl | 3 +- deps/rabbit_common/src/rabbit_env.erl | 4 +- .../src/rabbit_framing_amqp_0_8.erl | 3 +- .../src/rabbit_framing_amqp_0_9_1.erl | 3 +- deps/rabbit_common/src/rabbit_log.erl | 118 ----------------- deps/rabbit_common/src/rabbit_misc.erl | 9 +- .../rabbit_common/src/rabbit_nodes_common.erl | 5 +- deps/rabbit_common/src/rabbit_ssl_options.erl | 7 +- deps/rabbit_common/src/rabbit_writer.erl | 5 +- deps/rabbit_common/src/worker_pool_sup.erl | 7 +- .../src/rabbit_auth_backend_cache.erl | 7 +- .../src/rabbit_auth_backend_http.erl | 11 +- .../src/rabbit_auth_backend_oauth2.erl | 7 +- .../src/rabbit_oauth2_provider.erl | 5 +- .../src/uaa_jwt.erl | 19 +-- .../src/wildcard.erl | 5 +- .../src/rabbit_auth_mechanism_ssl.erl | 3 +- deps/rabbitmq_aws/src/rabbitmq_aws.erl | 25 ++-- deps/rabbitmq_aws/src/rabbitmq_aws_config.erl | 17 +-- .../src/rabbit_db_ch_exchange.erl | 5 +- .../rabbit_exchange_type_consistent_hash.erl | 23 ++-- .../src/rabbit_federation_exchange_link.erl | 7 +- .../src/rabbit_db_jms_exchange.erl | 5 +- .../src/rabbit_mgmt_app.erl | 9 +- .../src/rabbit_mgmt_db.erl | 7 +- .../src/rabbit_mgmt_util.erl | 25 ++-- .../src/rabbit_mgmt_wm_bindings.erl | 3 +- .../rabbit_mgmt_wm_connection_sessions.erl | 3 +- .../rabbit_mgmt_wm_connection_user_name.erl | 5 +- .../src/rabbit_mgmt_wm_definitions.erl | 9 +- .../src/rabbit_mgmt_wm_rebalance_queues.erl | 3 +- .../src/rabbit_mgmt_wm_vhost.erl | 3 +- ...bbit_mgmt_wm_vhost_deletion_protection.erl | 9 +- .../src/rabbit_mgmt_db_handler.erl | 7 +- .../src/rabbit_mgmt_external_stats.erl | 9 +- .../src/rabbit_mgmt_storage.erl | 3 +- .../rabbit_mqtt_internal_event_handler.erl | 5 +- .../src/rabbit_peer_discovery_aws.erl | 33 ++--- ...r_discovery_consul_health_check_helper.erl | 3 +- .../src/rabbit_peer_discovery_etcd.erl | 9 +- ...rabbitmq_peer_discovery_etcd_v3_client.erl | 71 +++++----- ...theus_rabbitmq_alarm_metrics_collector.erl | 3 +- .../src/rabbit_prometheus_app.erl | 7 +- .../src/rabbit_sharding_shard.erl | 5 +- .../src/rabbit_amqp091_shovel.erl | 11 +- .../src/rabbit_shovel_dyn_worker_sup.erl | 5 +- .../src/rabbit_shovel_parameters.erl | 3 +- .../src/rabbit_shovel_util.erl | 5 +- .../src/rabbit_shovel_mgmt_shovel.erl | 19 +-- deps/rabbitmq_stomp/src/rabbit_stomp.erl | 9 +- .../rabbit_stomp_internal_event_handler.erl | 5 +- .../src/rabbit_stomp_processor.erl | 13 +- deps/rabbitmq_stream/src/rabbit_stream.erl | 5 +- .../src/rabbit_stream_manager.erl | 45 +++---- .../src/rabbit_stream_reader.erl | 123 +++++++++--------- .../src/rabbit_stream_utils.erl | 5 +- .../src/rabbit_stream_mgmt_db.erl | 3 +- .../src/rabbit_tracing_consumer.erl | 5 +- .../src/rabbit_tracing_files.erl | 3 +- .../src/rabbit_tracing_util.erl | 5 +- .../src/rabbit_trust_store.erl | 19 +-- .../src/rabbit_trust_store_app.erl | 5 +- .../src/rabbit_trust_store_file_provider.erl | 3 +- .../src/rabbit_trust_store_http_provider.erl | 11 +- .../rabbit_web_dispatch_access_control.erl | 13 +- .../src/rabbit_web_dispatch_registry.erl | 7 +- .../src/rabbit_web_dispatch_sup.erl | 5 +- .../src/rabbit_web_mqtt_app.erl | 11 +- ...abbit_web_stomp_internal_event_handler.erl | 5 +- 153 files changed, 1213 insertions(+), 1115 deletions(-) delete mode 100644 deps/rabbit_common/src/rabbit_log.erl diff --git a/deps/oauth2_client/src/oauth2_client.erl b/deps/oauth2_client/src/oauth2_client.erl index f5d4f0f43361..56bb085a8c9c 100644 --- a/deps/oauth2_client/src/oauth2_client.erl +++ b/deps/oauth2_client/src/oauth2_client.erl @@ -17,12 +17,13 @@ ]). -include("oauth2_client.hrl"). +-include_lib("kernel/include/logger.hrl"). -spec get_access_token(oauth_provider(), access_token_request()) -> {ok, successful_access_token_response()} | {error, unsuccessful_access_token_response() | any()}. get_access_token(OAuthProvider, Request) -> - rabbit_log:debug("get_access_token using OAuthProvider:~p and client_id:~p", + ?LOG_DEBUG("get_access_token using OAuthProvider:~p and client_id:~p", [OAuthProvider, Request#access_token_request.client_id]), URL = OAuthProvider#oauth_provider.token_endpoint, Header = [], @@ -96,7 +97,7 @@ drop_trailing_path_separator(Path) when is_list(Path) -> -spec get_openid_configuration(DiscoveryEndpoint :: uri_string:uri_string(), ssl:tls_option() | []) -> {ok, openid_configuration()} | {error, term()}. get_openid_configuration(DiscoverEndpoint, TLSOptions) -> - rabbit_log:debug("get_openid_configuration from ~p (~p)", [DiscoverEndpoint, + ?LOG_DEBUG("get_openid_configuration from ~p (~p)", [DiscoverEndpoint, format_ssl_options(TLSOptions)]), Options = [], Response = httpc:request(get, {DiscoverEndpoint, []}, TLSOptions, Options), @@ -219,7 +220,7 @@ do_update_oauth_provider_endpoints_configuration(OAuthProvider) when undefined -> do_nothing; JwksUri -> set_env(jwks_uri, JwksUri) end, - rabbit_log:debug("Updated oauth_provider details: ~p ", + ?LOG_DEBUG("Updated oauth_provider details: ~p ", [format_oauth_provider(OAuthProvider)]), OAuthProvider; @@ -230,7 +231,7 @@ do_update_oauth_provider_endpoints_configuration(OAuthProvider) -> ModifiedOAuthProviders = maps:put(OAuthProviderId, merge_oauth_provider(OAuthProvider, Proplist), OAuthProviders), set_env(oauth_providers, ModifiedOAuthProviders), - rabbit_log:debug("Replaced oauth_providers "), + ?LOG_DEBUG("Replaced oauth_providers "), OAuthProvider. use_global_locks_on_all_nodes() -> @@ -271,7 +272,7 @@ get_oauth_provider(ListOfRequiredAttributes) -> case get_env(default_oauth_provider) of undefined -> get_root_oauth_provider(ListOfRequiredAttributes); DefaultOauthProviderId -> - rabbit_log:debug("Using default_oauth_provider ~p", + ?LOG_DEBUG("Using default_oauth_provider ~p", [DefaultOauthProviderId]), get_oauth_provider(DefaultOauthProviderId, ListOfRequiredAttributes) end. @@ -282,7 +283,7 @@ download_oauth_provider(OAuthProvider) -> case OAuthProvider#oauth_provider.discovery_endpoint of undefined -> {error, {missing_oauth_provider_attributes, [issuer]}}; URL -> - rabbit_log:debug("Downloading oauth_provider using ~p ", [URL]), + ?LOG_DEBUG("Downloading oauth_provider using ~p ", [URL]), case get_openid_configuration(URL, get_ssl_options_if_any(OAuthProvider)) of {ok, OpenIdConfiguration} -> {ok, update_oauth_provider_endpoints_configuration( @@ -294,7 +295,7 @@ download_oauth_provider(OAuthProvider) -> ensure_oauth_provider_has_attributes(OAuthProvider, ListOfRequiredAttributes) -> case find_missing_attributes(OAuthProvider, ListOfRequiredAttributes) of [] -> - rabbit_log:debug("Resolved oauth_provider ~p", + ?LOG_DEBUG("Resolved oauth_provider ~p", [format_oauth_provider(OAuthProvider)]), {ok, OAuthProvider}; _ = Attrs -> @@ -303,13 +304,13 @@ ensure_oauth_provider_has_attributes(OAuthProvider, ListOfRequiredAttributes) -> get_root_oauth_provider(ListOfRequiredAttributes) -> OAuthProvider = lookup_root_oauth_provider(), - rabbit_log:debug("Using root oauth_provider ~p", + ?LOG_DEBUG("Using root oauth_provider ~p", [format_oauth_provider(OAuthProvider)]), case find_missing_attributes(OAuthProvider, ListOfRequiredAttributes) of [] -> {ok, OAuthProvider}; _ = MissingAttributes -> - rabbit_log:debug("Looking up missing attributes ~p ...", + ?LOG_DEBUG("Looking up missing attributes ~p ...", [MissingAttributes]), case download_oauth_provider(OAuthProvider) of {ok, OAuthProvider2} -> @@ -333,22 +334,22 @@ get_oauth_provider(OAuth2ProviderId, ListOfRequiredAttributes) get_oauth_provider(OAuthProviderId, ListOfRequiredAttributes) when is_binary(OAuthProviderId) -> - rabbit_log:debug("get_oauth_provider ~p with at least these attributes: ~p", + ?LOG_DEBUG("get_oauth_provider ~p with at least these attributes: ~p", [OAuthProviderId, ListOfRequiredAttributes]), case lookup_oauth_provider_config(OAuthProviderId) of {error, _} = Error0 -> - rabbit_log:debug("Failed to find oauth_provider ~p configuration due to ~p", + ?LOG_DEBUG("Failed to find oauth_provider ~p configuration due to ~p", [OAuthProviderId, Error0]), Error0; Config -> - rabbit_log:debug("Found oauth_provider configuration ~p", [Config]), + ?LOG_DEBUG("Found oauth_provider configuration ~p", [Config]), OAuthProvider = map_to_oauth_provider(Config), - rabbit_log:debug("Resolved oauth_provider ~p", [format_oauth_provider(OAuthProvider)]), + ?LOG_DEBUG("Resolved oauth_provider ~p", [format_oauth_provider(OAuthProvider)]), case find_missing_attributes(OAuthProvider, ListOfRequiredAttributes) of [] -> {ok, OAuthProvider}; _ = MissingAttributes -> - rabbit_log:debug("OauthProvider has following missing attributes ~p", [MissingAttributes]), + ?LOG_DEBUG("OauthProvider has following missing attributes ~p", [MissingAttributes]), case download_oauth_provider(OAuthProvider) of {ok, OAuthProvider2} -> ensure_oauth_provider_has_attributes(OAuthProvider2, diff --git a/deps/rabbit/include/rabbit_amqp.hrl b/deps/rabbit/include/rabbit_amqp.hrl index 44e7d1522b57..3ba6e93ce811 100644 --- a/deps/rabbit/include/rabbit_amqp.hrl +++ b/deps/rabbit/include/rabbit_amqp.hrl @@ -3,7 +3,7 @@ -ifdef(TRACE_AMQP). -warning("AMQP tracing is enabled"). -define(TRACE(Format, Args), - rabbit_log:debug( + ?LOG_DEBUG( "~s:~s/~b ~b~n" ++ Format ++ "~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY, ?LINE] ++ Args)). -else. diff --git a/deps/rabbit/src/code_server_cache.erl b/deps/rabbit/src/code_server_cache.erl index 522269a48e7f..f9e516bbef92 100644 --- a/deps/rabbit/src/code_server_cache.erl +++ b/deps/rabbit/src/code_server_cache.erl @@ -9,6 +9,8 @@ -module(code_server_cache). +-include_lib("kernel/include/logger.hrl"). + -behaviour(gen_server). %% API @@ -70,7 +72,7 @@ handle_maybe_call_mfa(true, {Module, Function, Args, Default}, State) -> error:undef -> handle_maybe_call_mfa_error(Module, Default, State); Err:Reason -> - rabbit_log:error("Calling ~tp:~tp failed: ~tp:~tp", + ?LOG_ERROR("Calling ~tp:~tp failed: ~tp:~tp", [Module, Function, Err, Reason]), handle_maybe_call_mfa_error(Module, Default, State) end. diff --git a/deps/rabbit/src/file_handle_cache.erl b/deps/rabbit/src/file_handle_cache.erl index 813a01231c02..6e4c2bfe1087 100644 --- a/deps/rabbit/src/file_handle_cache.erl +++ b/deps/rabbit/src/file_handle_cache.erl @@ -7,6 +7,8 @@ -module(file_handle_cache). +-include_lib("kernel/include/logger.hrl"). + %% A File Handle Cache %% %% This extends a subset of the functionality of the Erlang file @@ -1451,19 +1453,19 @@ update_counts(open, Pid, Delta, State = #fhc_state { open_count = OpenCount, clients = Clients }) -> safe_ets_update_counter(Clients, Pid, {#cstate.opened, Delta}, - fun() -> rabbit_log:warning("FHC: failed to update counter 'opened', client pid: ~p", [Pid]) end), + fun() -> ?LOG_WARNING("FHC: failed to update counter 'opened', client pid: ~p", [Pid]) end), State #fhc_state { open_count = OpenCount + Delta}; update_counts({obtain, file}, Pid, Delta, State = #fhc_state {obtain_count_file = ObtainCountF, clients = Clients }) -> safe_ets_update_counter(Clients, Pid, {#cstate.obtained_file, Delta}, - fun() -> rabbit_log:warning("FHC: failed to update counter 'obtained_file', client pid: ~p", [Pid]) end), + fun() -> ?LOG_WARNING("FHC: failed to update counter 'obtained_file', client pid: ~p", [Pid]) end), State #fhc_state { obtain_count_file = ObtainCountF + Delta}; update_counts({obtain, socket}, Pid, Delta, State = #fhc_state {obtain_count_socket = ObtainCountS, clients = Clients }) -> safe_ets_update_counter(Clients, Pid, {#cstate.obtained_socket, Delta}, - fun() -> rabbit_log:warning("FHC: failed to update counter 'obtained_socket', client pid: ~p", [Pid]) end), + fun() -> ?LOG_WARNING("FHC: failed to update counter 'obtained_socket', client pid: ~p", [Pid]) end), State #fhc_state { obtain_count_socket = ObtainCountS + Delta}; update_counts({reserve, file}, Pid, NewReservation, State = #fhc_state {reserve_count_file = ReserveCountF, @@ -1471,7 +1473,7 @@ update_counts({reserve, file}, Pid, NewReservation, [#cstate{reserved_file = R}] = ets:lookup(Clients, Pid), Delta = NewReservation - R, safe_ets_update_counter(Clients, Pid, {#cstate.reserved_file, Delta}, - fun() -> rabbit_log:warning("FHC: failed to update counter 'reserved_file', client pid: ~p", [Pid]) end), + fun() -> ?LOG_WARNING("FHC: failed to update counter 'reserved_file', client pid: ~p", [Pid]) end), State #fhc_state { reserve_count_file = ReserveCountF + Delta}; update_counts({reserve, socket}, Pid, NewReservation, State = #fhc_state {reserve_count_socket = ReserveCountS, @@ -1479,7 +1481,7 @@ update_counts({reserve, socket}, Pid, NewReservation, [#cstate{reserved_file = R}] = ets:lookup(Clients, Pid), Delta = NewReservation - R, safe_ets_update_counter(Clients, Pid, {#cstate.reserved_socket, Delta}, - fun() -> rabbit_log:warning("FHC: failed to update counter 'reserved_socket', client pid: ~p", [Pid]) end), + fun() -> ?LOG_WARNING("FHC: failed to update counter 'reserved_socket', client pid: ~p", [Pid]) end), State #fhc_state { reserve_count_socket = ReserveCountS + Delta}. maybe_reduce(State) -> diff --git a/deps/rabbit/src/mc_compat.erl b/deps/rabbit/src/mc_compat.erl index 5fce91b202a4..1f11bc4bfef4 100644 --- a/deps/rabbit/src/mc_compat.erl +++ b/deps/rabbit/src/mc_compat.erl @@ -3,6 +3,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include_lib("rabbit_common/include/rabbit_framing.hrl"). -include("mc.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([ %init/3, @@ -267,7 +268,7 @@ update_x_death_header(Info, Headers) -> Headers, <<"x-death">>, array, [{table, rabbit_misc:sort_field_table(Info1)} | Others]); {<<"x-death">>, InvalidType, Header} -> - rabbit_log:warning("Message has invalid x-death header (type: ~tp)." + ?LOG_WARNING("Message has invalid x-death header (type: ~tp)." " Resetting header ~tp", [InvalidType, Header]), %% if x-death is something other than an array (list) diff --git a/deps/rabbit/src/mirrored_supervisor.erl b/deps/rabbit/src/mirrored_supervisor.erl index 201947072977..30f842858ef1 100644 --- a/deps/rabbit/src/mirrored_supervisor.erl +++ b/deps/rabbit/src/mirrored_supervisor.erl @@ -7,6 +7,8 @@ -module(mirrored_supervisor). +-include_lib("kernel/include/logger.hrl"). + %% Mirrored Supervisor %% =================== %% @@ -252,13 +254,13 @@ handle_call({init, Overall}, _From, LockId = mirrored_supervisor_locks:lock(Group), maybe_log_lock_acquisition_failure(LockId, Group), ok = pg:join(Group, Overall), - rabbit_log:debug("Mirrored supervisor: initializing, overall supervisor ~tp joined group ~tp", [Overall, Group]), + ?LOG_DEBUG("Mirrored supervisor: initializing, overall supervisor ~tp joined group ~tp", [Overall, Group]), Rest = pg:get_members(Group) -- [Overall], Nodes = [node(M) || M <- Rest], - rabbit_log:debug("Mirrored supervisor: known group ~tp members: ~tp on nodes ~tp", [Group, Rest, Nodes]), + ?LOG_DEBUG("Mirrored supervisor: known group ~tp members: ~tp on nodes ~tp", [Group, Rest, Nodes]), case Rest of [] -> - rabbit_log:debug("Mirrored supervisor: no known peer members in group ~tp, will delete all child records for it", [Group]), + ?LOG_DEBUG("Mirrored supervisor: no known peer members in group ~tp, will delete all child records for it", [Group]), delete_all(Group); _ -> ok end, @@ -282,18 +284,18 @@ handle_call({start_child, ChildSpec}, _From, group = Group}) -> LockId = mirrored_supervisor_locks:lock(Group), maybe_log_lock_acquisition_failure(LockId, Group), - rabbit_log:debug("Mirrored supervisor: asked to consider starting a child, group: ~tp", [Group]), + ?LOG_DEBUG("Mirrored supervisor: asked to consider starting a child, group: ~tp", [Group]), Result = case maybe_start(Group, Overall, Delegate, ChildSpec) of already_in_store -> - rabbit_log:debug("Mirrored supervisor: maybe_start for group ~tp," + ?LOG_DEBUG("Mirrored supervisor: maybe_start for group ~tp," " overall ~p returned 'record already present'", [Group, Overall]), {error, already_present}; {already_in_store, Pid} -> - rabbit_log:debug("Mirrored supervisor: maybe_start for group ~tp," + ?LOG_DEBUG("Mirrored supervisor: maybe_start for group ~tp," " overall ~p returned 'already running: ~tp'", [Group, Overall, Pid]), {error, {already_started, Pid}}; Else -> - rabbit_log:debug("Mirrored supervisor: maybe_start for group ~tp," + ?LOG_DEBUG("Mirrored supervisor: maybe_start for group ~tp," " overall ~tp returned ~tp", [Group, Overall, Else]), Else end, @@ -377,19 +379,19 @@ tell_all_peers_to_die(Group, Reason) -> [cast(P, {die, Reason}) || P <- pg:get_members(Group) -- [self()]]. maybe_start(Group, Overall, Delegate, ChildSpec) -> - rabbit_log:debug("Mirrored supervisor: asked to consider starting, group: ~tp", + ?LOG_DEBUG("Mirrored supervisor: asked to consider starting, group: ~tp", [Group]), try check_start(Group, Overall, Delegate, ChildSpec) of start -> - rabbit_log:debug("Mirrored supervisor: check_start for group ~tp," + ?LOG_DEBUG("Mirrored supervisor: check_start for group ~tp," " overall ~tp returned 'do start'", [Group, Overall]), start(Delegate, ChildSpec); undefined -> - rabbit_log:debug("Mirrored supervisor: check_start for group ~tp," + ?LOG_DEBUG("Mirrored supervisor: check_start for group ~tp," " overall ~tp returned 'undefined'", [Group, Overall]), already_in_store; Pid -> - rabbit_log:debug("Mirrored supervisor: check_start for group ~tp," + ?LOG_DEBUG("Mirrored supervisor: check_start for group ~tp," " overall ~tp returned 'already running (~tp)'", [Group, Overall, Pid]), {already_in_store, Pid} @@ -400,7 +402,7 @@ maybe_start(Group, Overall, Delegate, ChildSpec) -> check_start(Group, Overall, Delegate, ChildSpec) -> Id = id(ChildSpec), - rabbit_log:debug("Mirrored supervisor: check_start for group ~tp, id: ~tp, " + ?LOG_DEBUG("Mirrored supervisor: check_start for group ~tp, id: ~tp, " "overall: ~tp", [Group, Id, Overall]), case rabbit_db_msup:create_or_update(Group, Overall, Delegate, ChildSpec, Id) of Delegate0 when is_pid(Delegate0) -> @@ -486,6 +488,6 @@ restore_child_order(ChildSpecs, ChildOrder) -> end, ChildSpecs). maybe_log_lock_acquisition_failure(undefined = _LockId, Group) -> - rabbit_log:warning("Mirrored supervisor: could not acquire lock for group ~ts", [Group]); + ?LOG_WARNING("Mirrored supervisor: could not acquire lock for group ~ts", [Group]); maybe_log_lock_acquisition_failure(_, _) -> ok. diff --git a/deps/rabbit/src/rabbit.erl b/deps/rabbit/src/rabbit.erl index 3657f60f05bd..86e74f763fef 100644 --- a/deps/rabbit/src/rabbit.erl +++ b/deps/rabbit/src/rabbit.erl @@ -1688,7 +1688,7 @@ maybe_warn_low_fd_limit() -> L when L > 1024 -> ok; L -> - rabbit_log:warning("Available file handles: ~tp. " + ?LOG_WARNING("Available file handles: ~tp. " "Please consider increasing system limits", [L]) end. @@ -1718,7 +1718,7 @@ persist_static_configuration() -> MoreCreditAfter =< InitialCredit -> {InitialCredit, MoreCreditAfter}; Other -> - rabbit_log:error("Refusing to boot due to an invalid value of 'rabbit.credit_flow_default_credit'"), + ?LOG_ERROR("Refusing to boot due to an invalid value of 'rabbit.credit_flow_default_credit'"), throw({error, {invalid_credit_flow_default_credit_value, Other}}) end, ok = persistent_term:put(credit_flow_default_credit, CreditFlowDefaultCredit), diff --git a/deps/rabbit/src/rabbit_access_control.erl b/deps/rabbit/src/rabbit_access_control.erl index 4ff752c4538c..3fb09726b237 100644 --- a/deps/rabbit/src/rabbit_access_control.erl +++ b/deps/rabbit/src/rabbit_access_control.erl @@ -8,6 +8,7 @@ -module(rabbit_access_control). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([check_user_pass_login/2, check_user_login/2, check_user_login/3, check_user_loopback/2, check_vhost_access/4, check_resource_access/4, check_topic_access/4, @@ -59,10 +60,10 @@ check_user_login(Username, AuthProps, Modules) -> %% it gives us case try_authenticate(Mod, Username, AuthProps) of {ok, ModNUser = #auth_user{username = Username2, impl = Impl}} -> - rabbit_log:debug("User '~ts' authenticated successfully by backend ~ts", [Username2, Mod]), + ?LOG_DEBUG("User '~ts' authenticated successfully by backend ~ts", [Username2, Mod]), user(ModNUser, {ok, [{Mod, Impl}], []}); Else -> - rabbit_log:debug("User '~ts' failed authentication by backend ~ts", [Username, Mod]), + ?LOG_DEBUG("User '~ts' failed authentication by backend ~ts", [Username, Mod]), Else end; (_, {ok, User}) -> @@ -72,7 +73,7 @@ check_user_login(Username, AuthProps, Modules) -> {refused, Username, "No modules checked '~ts'", [Username]}, Modules) catch Type:Error:Stacktrace -> - rabbit_log:debug("User '~ts' authentication failed with ~ts:~tp:~n~tp", [Username, Type, Error, Stacktrace]), + ?LOG_DEBUG("User '~ts' authentication failed with ~ts:~tp:~n~tp", [Username, Type, Error, Stacktrace]), {refused, Username, "User '~ts' authentication failed with internal error. " "Enable debug logs to see the real error.", [Username]} @@ -85,7 +86,7 @@ try_authenticate_and_try_authorize(ModN, ModZs0, Username, AuthProps) -> end, case try_authenticate(ModN, Username, AuthProps) of {ok, ModNUser = #auth_user{username = Username2}} -> - rabbit_log:debug("User '~ts' authenticated successfully by backend ~ts", [Username2, ModN]), + ?LOG_DEBUG("User '~ts' authenticated successfully by backend ~ts", [Username2, ModN]), user(ModNUser, try_authorize(ModZs, Username2, AuthProps)); Else -> Else @@ -227,7 +228,7 @@ check_access(Fun, Module, ErrStr, ErrArgs, ErrName) -> {error, E} -> FullErrStr = ErrStr ++ ", backend ~ts returned an error: ~tp", FullErrArgs = ErrArgs ++ [Module, E], - rabbit_log:error(FullErrStr, FullErrArgs), + ?LOG_ERROR(FullErrStr, FullErrArgs), rabbit_misc:protocol_error(ErrName, FullErrStr, FullErrArgs) end. diff --git a/deps/rabbit/src/rabbit_alarm.erl b/deps/rabbit/src/rabbit_alarm.erl index ef5b55dfa9f8..969e614f4a59 100644 --- a/deps/rabbit/src/rabbit_alarm.erl +++ b/deps/rabbit/src/rabbit_alarm.erl @@ -18,6 +18,8 @@ -module(rabbit_alarm). +-include_lib("kernel/include/logger.hrl"). + -behaviour(gen_event). -export([start_link/0, start/0, stop/0, register/2, set_alarm/1, @@ -239,7 +241,7 @@ handle_event({node_down, Node}, #alarms{alarmed_nodes = AN} = State) -> error -> [] end, {ok, lists:foldr(fun(Source, AccState) -> - rabbit_log:warning("~ts resource limit alarm cleared for dead node ~tp", + ?LOG_WARNING("~ts resource limit alarm cleared for dead node ~tp", [Source, Node]), maybe_alert(fun dict_unappend/3, Node, Source, false, AccState) end, State, AlarmsForDeadNode)}; @@ -291,7 +293,7 @@ maybe_alert(UpdateFun, Node, Source, WasAlertAdded, StillHasAlerts = lists:any(fun ({_Node, NodeAlerts}) -> lists:member(Source, NodeAlerts) end, dict:to_list(AN1)), case StillHasAlerts of true -> ok; - false -> rabbit_log:warning("~ts resource limit alarm cleared across the cluster", [Source]) + false -> ?LOG_WARNING("~ts resource limit alarm cleared across the cluster", [Source]) end, Alert = {WasAlertAdded, StillHasAlerts, Node}, case node() of @@ -327,7 +329,7 @@ internal_register(Pid, {M, F, A} = AlertMFA, State#alarms{alertees = NewAlertees}. handle_set_resource_alarm(Source, Node, State) -> - rabbit_log:warning( + ?LOG_WARNING( "~ts resource limit alarm set on node ~tp.~n~n" "**********************************************************~n" "*** Publishers will be blocked until this alarm clears ***~n" @@ -336,26 +338,26 @@ handle_set_resource_alarm(Source, Node, State) -> {ok, maybe_alert(fun dict_append/3, Node, Source, true, State)}. handle_set_alarm({file_descriptor_limit, []}, State) -> - rabbit_log:warning( + ?LOG_WARNING( "file descriptor limit alarm set.~n~n" "********************************************************************~n" "*** New connections will not be accepted until this alarm clears ***~n" "********************************************************************~n"), {ok, State}; handle_set_alarm(Alarm, State) -> - rabbit_log:warning("alarm '~tp' set", [Alarm]), + ?LOG_WARNING("alarm '~tp' set", [Alarm]), {ok, State}. handle_clear_resource_alarm(Source, Node, State) -> - rabbit_log:warning("~ts resource limit alarm cleared on node ~tp", + ?LOG_WARNING("~ts resource limit alarm cleared on node ~tp", [Source, Node]), {ok, maybe_alert(fun dict_unappend/3, Node, Source, false, State)}. handle_clear_alarm(file_descriptor_limit, State) -> - rabbit_log:warning("file descriptor limit alarm cleared~n"), + ?LOG_WARNING("file descriptor limit alarm cleared~n"), {ok, State}; handle_clear_alarm(Alarm, State) -> - rabbit_log:warning("alarm '~tp' cleared", [Alarm]), + ?LOG_WARNING("alarm '~tp' cleared", [Alarm]), {ok, State}. is_node_alarmed(Source, Node, #alarms{alarmed_nodes = AN}) -> diff --git a/deps/rabbit/src/rabbit_amqp_filter_sql.erl b/deps/rabbit/src/rabbit_amqp_filter_sql.erl index 0d7b1768bfb9..25341719dcde 100644 --- a/deps/rabbit/src/rabbit_amqp_filter_sql.erl +++ b/deps/rabbit/src/rabbit_amqp_filter_sql.erl @@ -8,6 +8,7 @@ -feature(maybe_expr, enable). -include_lib("amqp10_common/include/amqp10_filter.hrl"). +-include_lib("kernel/include/logger.hrl"). -type parsed_expression() :: {ApplicationProperties :: boolean(), rabbit_amqp_sql_ast:ast()}. @@ -293,36 +294,33 @@ sql_to_list(SQL) -> String when is_list(String) -> {ok, String}; Error -> - rabbit_log:warning("SQL expression ~p is not UTF-8 encoded: ~p", - [SQL, Error]), + ?LOG_WARNING("JMS message selector ~p is not UTF-8 encoded: ~p", + [JmsSelector, Error]), error end. -check_length(String) -> - Len = length(String), - case Len =< ?MAX_EXPRESSION_LENGTH of - true -> - ok; - false -> - rabbit_log:warning("SQL expression length ~b exceeds maximum length ~b", - [Len, ?MAX_EXPRESSION_LENGTH]), - error - end. +check_length(String) + when length(String) > ?MAX_EXPRESSION_LENGTH -> + ?LOG_WARNING("JMS message selector length ~b exceeds maximum length ~b", + [length(String), ?MAX_EXPRESSION_LENGTH]), + error; +check_length(_) -> + ok. tokenize(String, SQL) -> case rabbit_amqp_sql_lexer:string(String) of {ok, Tokens, _EndLocation} -> {ok, Tokens}; {error, {_Line, _Mod, ErrDescriptor}, _Location} -> - rabbit_log:warning("failed to scan SQL expression '~ts': ~tp", - [SQL, ErrDescriptor]), + ?LOG_WARNING("failed to scan JMS message selector '~ts': ~tp", + [JmsSelector, ErrDescriptor]), error end. check_token_count(Tokens, SQL) when length(Tokens) > ?MAX_TOKENS -> - rabbit_log:warning("SQL expression '~ts' with ~b tokens exceeds token limit ~b", - [SQL, length(Tokens), ?MAX_TOKENS]), + ?LOG_WARNING("JMS message selector '~ts' with ~b tokens exceeds token limit ~b", + [JmsSelector, length(Tokens), ?MAX_TOKENS]), error; check_token_count(_, _) -> ok. @@ -330,8 +328,8 @@ check_token_count(_, _) -> parse(Tokens, SQL) -> case rabbit_amqp_sql_parser:parse(Tokens) of {error, Reason} -> - rabbit_log:warning("failed to parse SQL expression '~ts': ~p", - [SQL, Reason]), + ?LOG_WARNING("failed to parse JMS message selector '~ts': ~p", + [JmsSelector, Reason]), error; Ok -> Ok @@ -345,10 +343,15 @@ transform_ast(Ast0, SQL) -> end, Ast0) of Ast -> {ok, Ast} - catch {invalid_pattern, Reason} -> - rabbit_log:warning( - "failed to parse LIKE pattern for SQL expression ~tp: ~tp", - [SQL, Reason]), + catch {unsupported_field, Name} -> + ?LOG_WARNING( + "identifier ~ts in JMS message selector ~tp is unsupported", + [Name, JmsSelector]), + error; + {invalid_pattern, Reason} -> + ?LOG_WARNING( + "failed to parse LIKE pattern for JMS message selector ~tp: ~tp", + [JmsSelector, Reason]), error end. diff --git a/deps/rabbit/src/rabbit_amqp_management.erl b/deps/rabbit/src/rabbit_amqp_management.erl index 7e7fb84da6fa..7769c7c7327f 100644 --- a/deps/rabbit/src/rabbit_amqp_management.erl +++ b/deps/rabbit/src/rabbit_amqp_management.erl @@ -2,6 +2,7 @@ -include("rabbit_amqp.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([handle_request/5]). @@ -49,7 +50,7 @@ handle_request(Request, Vhost, User, ConnectionPid, PermCaches0) -> ConnectionPid, PermCaches0) catch throw:{?MODULE, StatusCode0, Explanation} -> - rabbit_log:warning("request ~ts ~ts failed: ~ts", + ?LOG_WARNING("request ~ts ~ts failed: ~ts", [HttpMethod, HttpRequestTarget, Explanation]), {StatusCode0, {utf8, Explanation}, PermCaches0} end, diff --git a/deps/rabbit/src/rabbit_amqqueue.erl b/deps/rabbit/src/rabbit_amqqueue.erl index c2f954ccbfdc..041cb52cc75f 100644 --- a/deps/rabbit/src/rabbit_amqqueue.erl +++ b/deps/rabbit/src/rabbit_amqqueue.erl @@ -82,6 +82,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include_lib("stdlib/include/qlc.hrl"). -include("amqqueue.hrl"). +-include_lib("kernel/include/logger.hrl"). -define(INTEGER_ARG_TYPES, [byte, short, signedint, long, unsignedbyte, unsignedshort, unsignedint]). @@ -423,7 +424,7 @@ rebalance(Type, VhostSpec, QueueSpec) -> %% TODO: classic queues do not support rebalancing, it looks like they are simply %% filtered out with is_replicable(Q). Maybe error instead? maybe_rebalance({true, Id}, Type, VhostSpec, QueueSpec) -> - rabbit_log:info("Starting queue rebalance operation: '~ts' for vhosts matching '~ts' and queues matching '~ts'", + ?LOG_INFO("Starting queue rebalance operation: '~ts' for vhosts matching '~ts' and queues matching '~ts'", [Type, VhostSpec, QueueSpec]), Running = rabbit_maintenance:filter_out_drained_nodes_consistent_read(rabbit_nodes:list_running()), NumRunning = length(Running), @@ -445,10 +446,10 @@ maybe_rebalance({true, Id}, Type, VhostSpec, QueueSpec) -> MaxQueuesDesired = (NumToRebalance div NumRunning) + Rem, Result = iterative_rebalance(ByNode, MaxQueuesDesired), global:del_lock(Id), - rabbit_log:info("Finished queue rebalance operation"), + ?LOG_INFO("Finished queue rebalance operation"), Result; maybe_rebalance(false, _Type, _VhostSpec, _QueueSpec) -> - rabbit_log:warning("Queue rebalance operation is in progress, please wait."), + ?LOG_WARNING("Queue rebalance operation is in progress, please wait."), {error, rebalance_in_progress}. %% Stream queues don't yet support rebalance @@ -466,7 +467,7 @@ filter_per_type_for_rebalance(TypeModule, Q) -> rebalance_module(Q) -> case rabbit_queue_type:rebalance_module(Q) of undefined -> - rabbit_log:error("Undefined rebalance module for queue type: ~s", [amqqueue:get_type(Q)]), + ?LOG_ERROR("Undefined rebalance module for queue type: ~s", [amqqueue:get_type(Q)]), {error, not_supported}; RBModule -> RBModule @@ -484,7 +485,7 @@ is_match(Subj, RegEx) -> iterative_rebalance(ByNode, MaxQueuesDesired) -> case maybe_migrate(ByNode, MaxQueuesDesired) of {ok, Summary} -> - rabbit_log:info("All queue leaders are balanced"), + ?LOG_INFO("All queue leaders are balanced"), {ok, Summary}; {migrated, Other} -> iterative_rebalance(Other, MaxQueuesDesired); @@ -521,23 +522,23 @@ maybe_migrate(ByNode, MaxQueuesDesired, [N | Nodes]) -> {not_migrated, update_not_migrated_queue(N, Queue, Queues, ByNode)}; _ -> [{Length, Destination} | _] = sort_by_number_of_queues(Candidates, ByNode), - rabbit_log:info("Migrating queue ~tp from node ~tp with ~tp queues to node ~tp with ~tp queues", + ?LOG_INFO("Migrating queue ~tp from node ~tp with ~tp queues to node ~tp with ~tp queues", [Name, N, length(All), Destination, Length]), case Module:transfer_leadership(Q, Destination) of {migrated, NewNode} -> - rabbit_log:info("Queue ~tp migrated to ~tp", [Name, NewNode]), + ?LOG_INFO("Queue ~tp migrated to ~tp", [Name, NewNode]), {migrated, update_migrated_queue(NewNode, N, Queue, Queues, ByNode)}; {not_migrated, Reason} -> - rabbit_log:warning("Error migrating queue ~tp: ~tp", [Name, Reason]), + ?LOG_WARNING("Error migrating queue ~tp: ~tp", [Name, Reason]), {not_migrated, update_not_migrated_queue(N, Queue, Queues, ByNode)} end end; [{_, _, true} | _] = All when length(All) > MaxQueuesDesired -> - rabbit_log:warning("Node ~tp contains ~tp queues, but all have already migrated. " + ?LOG_WARNING("Node ~tp contains ~tp queues, but all have already migrated. " "Do nothing", [N, length(All)]), maybe_migrate(ByNode, MaxQueuesDesired, Nodes); All -> - rabbit_log:debug("Node ~tp only contains ~tp queues, do nothing", + ?LOG_DEBUG("Node ~tp only contains ~tp queues, do nothing", [N, length(All)]), maybe_migrate(ByNode, MaxQueuesDesired, Nodes) end. @@ -625,7 +626,7 @@ retry_wait(Q, F, E, RetriesLeft) -> %% The old check would have crashed here, %% instead, log it and run the exit fun. absent & alive is weird, %% but better than crashing with badmatch,true - rabbit_log:debug("Unexpected alive queue process ~tp", [QPid]), + ?LOG_DEBUG("Unexpected alive queue process ~tp", [QPid]), E({absent, Q, alive}); false -> ok % Expected result @@ -1894,7 +1895,7 @@ internal_delete(Queue, ActingUser, Reason) -> %% TODO this is used by `rabbit_mnesia:remove_node_if_mnesia_running` %% Does it make any sense once mnesia is not used/removed? forget_all_durable(Node) -> - rabbit_log:info("Will remove all classic queues from node ~ts. The node is likely being removed from the cluster.", [Node]), + ?LOG_INFO("Will remove all classic queues from node ~ts. The node is likely being removed from the cluster.", [Node]), UpdateFun = fun(Q) -> forget_node_for_queue(Q) end, @@ -1959,7 +1960,7 @@ on_node_down(Node) -> %% `rabbit_khepri:init/0': we also try this deletion when the node %% restarts - a time that the cluster is very likely to have a %% majority - to ensure these records are deleted. - rabbit_log:warning("transient queues for node '~ts' could not be " + ?LOG_WARNING("transient queues for node '~ts' could not be " "deleted because of a timeout. These queues " "will be removed when node '~ts' restarts or " "is removed from the cluster.", [Node, Node]), @@ -1980,7 +1981,7 @@ delete_transient_queues_on_node(Node) -> {QueueNames, Deletions} when is_list(QueueNames) -> case length(QueueNames) of 0 -> ok; - N -> rabbit_log:info("~b transient queues from node '~ts' " + N -> ?LOG_INFO("~b transient queues from node '~ts' " "deleted in ~fs", [N, Node, Time / 1_000_000]) end, diff --git a/deps/rabbit/src/rabbit_amqqueue_process.erl b/deps/rabbit/src/rabbit_amqqueue_process.erl index 2e18d49010c3..1ad36a3cdd67 100644 --- a/deps/rabbit/src/rabbit_amqqueue_process.erl +++ b/deps/rabbit/src/rabbit_amqqueue_process.erl @@ -8,6 +8,7 @@ -module(rabbit_amqqueue_process). -include_lib("rabbit_common/include/rabbit.hrl"). -include("amqqueue.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(gen_server2). @@ -150,7 +151,7 @@ init({Q, Marker}) -> %% restart QueueName = amqqueue:get_name(Q), {ok, Q1} = rabbit_amqqueue:lookup(QueueName), - rabbit_log:error("Restarting crashed ~ts.", [rabbit_misc:rs(QueueName)]), + ?LOG_ERROR("Restarting crashed ~ts.", [rabbit_misc:rs(QueueName)]), gen_server2:cast(self(), init), init(Q1) end; @@ -1604,7 +1605,7 @@ handle_cast({force_event_refresh, Ref}, rabbit_event:notify(queue_created, queue_created_infos(State), Ref), QName = qname(State), AllConsumers = rabbit_queue_consumers:all(Consumers), - rabbit_log:debug("Queue ~ts forced to re-emit events, consumers: ~tp", [rabbit_misc:rs(QName), AllConsumers]), + ?LOG_DEBUG("Queue ~ts forced to re-emit events, consumers: ~tp", [rabbit_misc:rs(QName), AllConsumers]), [emit_consumer_created( Ch, CTag, ActiveOrExclusive, AckRequired, QName, Prefetch, Args, Ref, ActingUser) || diff --git a/deps/rabbit/src/rabbit_amqqueue_sup_sup.erl b/deps/rabbit/src/rabbit_amqqueue_sup_sup.erl index 87a80ba40f1e..e7cba35f5905 100644 --- a/deps/rabbit/src/rabbit_amqqueue_sup_sup.erl +++ b/deps/rabbit/src/rabbit_amqqueue_sup_sup.erl @@ -16,6 +16,7 @@ -export([init/1]). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -define(SERVER, ?MODULE). @@ -74,7 +75,7 @@ start_for_vhost(VHost) -> %% we can get here if a vhost is added and removed concurrently %% e.g. some integration tests do it {error, {no_such_vhost, VHost}} -> - rabbit_log:error("Failed to start a queue process supervisor for vhost ~ts: vhost no longer exists!", + ?LOG_ERROR("Failed to start a queue process supervisor for vhost ~ts: vhost no longer exists!", [VHost]), {error, {no_such_vhost, VHost}} end. @@ -87,7 +88,7 @@ stop_for_vhost(VHost) -> ok = supervisor:delete_child(VHostSup, rabbit_amqqueue_sup_sup); %% see start/1 {error, {no_such_vhost, VHost}} -> - rabbit_log:error("Failed to stop a queue process supervisor for vhost ~ts: vhost no longer exists!", + ?LOG_ERROR("Failed to stop a queue process supervisor for vhost ~ts: vhost no longer exists!", [VHost]), ok end. diff --git a/deps/rabbit/src/rabbit_auth_backend_internal.erl b/deps/rabbit/src/rabbit_auth_backend_internal.erl index 86e1df0688fc..4b658f7794f6 100644 --- a/deps/rabbit/src/rabbit_auth_backend_internal.erl +++ b/deps/rabbit/src/rabbit_auth_backend_internal.erl @@ -7,6 +7,7 @@ -module(rabbit_auth_backend_internal). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(rabbit_authn_backend). -behaviour(rabbit_authz_backend). @@ -204,7 +205,7 @@ validate_and_alternate_credentials(Username, Password, ActingUser, Fun) -> ok -> Fun(Username, Password, ActingUser); {error, Err} -> - rabbit_log:error("Credential validation for user '~ts' failed!", [Username]), + ?LOG_ERROR("Credential validation for user '~ts' failed!", [Username]), {error, Err} end. @@ -238,7 +239,7 @@ add_user_sans_validation(Limits, Tags) -> end. add_user_sans_validation(Username, Password, ActingUser, Limits, Tags) -> - rabbit_log:debug("Asked to create a new user '~ts', password length in bytes: ~tp", [Username, bit_size(Password)]), + ?LOG_DEBUG("Asked to create a new user '~ts', password length in bytes: ~tp", [Username, bit_size(Password)]), %% hash_password will pick the hashing function configured for us %% but we also need to store a hint as part of the record, so we %% retrieve it here one more time @@ -254,7 +255,7 @@ add_user_sans_validation(Username, Password, ActingUser, Limits, Tags) -> add_user_sans_validation_in(Username, User, ConvertedTags, Limits, ActingUser). add_user_sans_validation(Username, PasswordHash, HashingMod, Tags, Limits, ActingUser) -> - rabbit_log:debug("Asked to create a new user '~ts' with password hash", [Username]), + ?LOG_DEBUG("Asked to create a new user '~ts' with password hash", [Username]), ConvertedTags = [rabbit_data_coercion:to_atom(I) || I <- Tags], User0 = internal_user:create_user(Username, PasswordHash, HashingMod), User1 = internal_user:set_tags( @@ -269,7 +270,7 @@ add_user_sans_validation(Username, PasswordHash, HashingMod, Tags, Limits, Actin add_user_sans_validation_in(Username, User, ConvertedTags, Limits, ActingUser) -> try R = rabbit_db_user:create(User), - rabbit_log:info("Created user '~ts'", [Username]), + ?LOG_INFO("Created user '~ts'", [Username]), rabbit_event:notify(user_created, [{name, Username}, {user_who_performed_action, ActingUser}]), case ConvertedTags of @@ -283,21 +284,21 @@ add_user_sans_validation_in(Username, User, ConvertedTags, Limits, ActingUser) - R catch throw:{error, {user_already_exists, _}} = Error -> - rabbit_log:warning("Failed to add user '~ts': the user already exists", [Username]), + ?LOG_WARNING("Failed to add user '~ts': the user already exists", [Username]), throw(Error); Class:Error:Stacktrace -> - rabbit_log:warning("Failed to add user '~ts': ~tp", [Username, Error]), + ?LOG_WARNING("Failed to add user '~ts': ~tp", [Username, Error]), erlang:raise(Class, Error, Stacktrace) end . -spec delete_user(rabbit_types:username(), rabbit_types:username()) -> 'ok'. delete_user(Username, ActingUser) -> - rabbit_log:debug("Asked to delete user '~ts'", [Username]), + ?LOG_DEBUG("Asked to delete user '~ts'", [Username]), try case rabbit_db_user:delete(Username) of true -> - rabbit_log:info("Deleted user '~ts'", [Username]), + ?LOG_INFO("Deleted user '~ts'", [Username]), rabbit_event:notify(user_deleted, [{name, Username}, {user_who_performed_action, ActingUser}]), @@ -305,12 +306,12 @@ delete_user(Username, ActingUser) -> false -> ok; Error0 -> - rabbit_log:info("Failed to delete user '~ts': ~tp", [Username, Error0]), + ?LOG_INFO("Failed to delete user '~ts': ~tp", [Username, Error0]), throw(Error0) end catch Class:Error:Stacktrace -> - rabbit_log:warning("Failed to delete user '~ts': ~tp", [Username, Error]), + ?LOG_WARNING("Failed to delete user '~ts': ~tp", [Username, Error]), erlang:raise(Class, Error, Stacktrace) end . @@ -342,23 +343,23 @@ change_password(Username, Password, ActingUser) -> change_password_sans_validation(Username, Password, ActingUser) -> try - rabbit_log:debug("Asked to change password of user '~ts', new password length in bytes: ~tp", [Username, bit_size(Password)]), + ?LOG_DEBUG("Asked to change password of user '~ts', new password length in bytes: ~tp", [Username, bit_size(Password)]), HashingAlgorithm = rabbit_password:hashing_mod(), R = change_password_hash(Username, hash_password(rabbit_password:hashing_mod(), Password), HashingAlgorithm), - rabbit_log:info("Successfully changed password for user '~ts'", [Username]), + ?LOG_INFO("Successfully changed password for user '~ts'", [Username]), rabbit_event:notify(user_password_changed, [{name, Username}, {user_who_performed_action, ActingUser}]), R catch throw:{error, {no_such_user, _}} = Error -> - rabbit_log:warning("Failed to change password for user '~ts': the user does not exist", [Username]), + ?LOG_WARNING("Failed to change password for user '~ts': the user does not exist", [Username]), throw(Error); Class:Error:Stacktrace -> - rabbit_log:warning("Failed to change password for user '~ts': ~tp", [Username, Error]), + ?LOG_WARNING("Failed to change password for user '~ts': ~tp", [Username, Error]), erlang:raise(Class, Error, Stacktrace) end. @@ -369,10 +370,10 @@ update_user(Username, Password, Tags, Limits, ActingUser) -> update_user_sans_validation(Tags, Limits) -> fun(Username, Password, ActingUser) -> try - rabbit_log:debug("Asked to change password of user '~ts', new password length in bytes: ~tp", [Username, bit_size(Password)]), + ?LOG_DEBUG("Asked to change password of user '~ts', new password length in bytes: ~tp", [Username, bit_size(Password)]), HashingAlgorithm = rabbit_password:hashing_mod(), - rabbit_log:debug("Asked to set user tags for user '~ts' to ~tp", [Username, Tags]), + ?LOG_DEBUG("Asked to set user tags for user '~ts' to ~tp", [Username, Tags]), ConvertedTags = [rabbit_data_coercion:to_atom(I) || I <- Tags], R = update_user_with_hash(Username, @@ -381,7 +382,7 @@ update_user_sans_validation(Tags, Limits) -> HashingAlgorithm, ConvertedTags, Limits), - rabbit_log:info("Successfully changed password for user '~ts'", [Username]), + ?LOG_INFO("Successfully changed password for user '~ts'", [Username]), rabbit_event:notify(user_password_changed, [{name, Username}, {user_who_performed_action, ActingUser}]), @@ -390,10 +391,10 @@ update_user_sans_validation(Tags, Limits) -> R catch throw:{error, {no_such_user, _}} = Error -> - rabbit_log:warning("Failed to change password for user '~ts': the user does not exist", [Username]), + ?LOG_WARNING("Failed to change password for user '~ts': the user does not exist", [Username]), throw(Error); Class:Error:Stacktrace -> - rabbit_log:warning("Failed to change password for user '~ts': ~tp", [Username, Error]), + ?LOG_WARNING("Failed to change password for user '~ts': ~tp", [Username, Error]), erlang:raise(Class, Error, Stacktrace) end end. @@ -401,7 +402,7 @@ update_user_sans_validation(Tags, Limits) -> -spec clear_password(rabbit_types:username(), rabbit_types:username()) -> 'ok'. clear_password(Username, ActingUser) -> - rabbit_log:info("Clearing password for user '~ts'", [Username]), + ?LOG_INFO("Clearing password for user '~ts'", [Username]), R = change_password_hash(Username, <<"">>), rabbit_event:notify(user_password_cleared, [{name, Username}, @@ -443,7 +444,7 @@ update_user_with_hash(Username, PasswordHash, HashingAlgorithm, ConvertedTags, L set_tags(Username, Tags, ActingUser) -> ConvertedTags = [rabbit_data_coercion:to_atom(I) || I <- Tags], - rabbit_log:debug("Asked to set user tags for user '~ts' to ~tp", [Username, ConvertedTags]), + ?LOG_DEBUG("Asked to set user tags for user '~ts' to ~tp", [Username, ConvertedTags]), try R = rabbit_db_user:update(Username, fun(User) -> internal_user:set_tags(User, ConvertedTags) @@ -452,15 +453,15 @@ set_tags(Username, Tags, ActingUser) -> R catch throw:{error, {no_such_user, _}} = Error -> - rabbit_log:warning("Failed to set tags for user '~ts': the user does not exist", [Username]), + ?LOG_WARNING("Failed to set tags for user '~ts': the user does not exist", [Username]), throw(Error); Class:Error:Stacktrace -> - rabbit_log:warning("Failed to set tags for user '~ts': ~tp", [Username, Error]), + ?LOG_WARNING("Failed to set tags for user '~ts': ~tp", [Username, Error]), erlang:raise(Class, Error, Stacktrace) end . notify_user_tags_set(Username, ConvertedTags, ActingUser) -> - rabbit_log:info("Successfully set user tags for user '~ts' to ~tp", [Username, ConvertedTags]), + ?LOG_INFO("Successfully set user tags for user '~ts' to ~tp", [Username, ConvertedTags]), rabbit_event:notify(user_tags_set, [{name, Username}, {tags, ConvertedTags}, {user_who_performed_action, ActingUser}]). @@ -470,7 +471,7 @@ notify_user_tags_set(Username, ConvertedTags, ActingUser) -> 'ok'. set_permissions(Username, VirtualHost, ConfigurePerm, WritePerm, ReadPerm, ActingUser) -> - rabbit_log:debug("Asked to set permissions for user " + ?LOG_DEBUG("Asked to set permissions for user " "'~ts' in virtual host '~ts' to '~ts', '~ts', '~ts'", [Username, VirtualHost, ConfigurePerm, WritePerm, ReadPerm]), _ = lists:map( @@ -479,7 +480,7 @@ set_permissions(Username, VirtualHost, ConfigurePerm, WritePerm, ReadPerm, Actin case re:compile(Regexp) of {ok, _} -> ok; {error, Reason} -> - rabbit_log:warning("Failed to set permissions for user '~ts' in virtual host '~ts': " + ?LOG_WARNING("Failed to set permissions for user '~ts' in virtual host '~ts': " "regular expression '~ts' is invalid", [Username, VirtualHost, RegexpBin]), throw({error, {invalid_regexp, Regexp, Reason}}) @@ -495,7 +496,7 @@ set_permissions(Username, VirtualHost, ConfigurePerm, WritePerm, ReadPerm, Actin write = WritePerm, read = ReadPerm}}, R = rabbit_db_user:set_user_permissions(UserPermission), - rabbit_log:info("Successfully set permissions for user " + ?LOG_INFO("Successfully set permissions for user " "'~ts' in virtual host '~ts' to '~ts', '~ts', '~ts'", [Username, VirtualHost, ConfigurePerm, WritePerm, ReadPerm]), rabbit_event:notify(permission_created, [{user, Username}, @@ -507,15 +508,15 @@ set_permissions(Username, VirtualHost, ConfigurePerm, WritePerm, ReadPerm, Actin R catch throw:{error, {no_such_vhost, _}} = Error -> - rabbit_log:warning("Failed to set permissions for user '~ts': virtual host '~ts' does not exist", + ?LOG_WARNING("Failed to set permissions for user '~ts': virtual host '~ts' does not exist", [Username, VirtualHost]), throw(Error); throw:{error, {no_such_user, _}} = Error -> - rabbit_log:warning("Failed to set permissions for user '~ts': the user does not exist", + ?LOG_WARNING("Failed to set permissions for user '~ts': the user does not exist", [Username]), throw(Error); Class:Error:Stacktrace -> - rabbit_log:warning("Failed to set permissions for user '~ts' in virtual host '~ts': ~tp", + ?LOG_WARNING("Failed to set permissions for user '~ts' in virtual host '~ts': ~tp", [Username, VirtualHost, Error]), erlang:raise(Class, Error, Stacktrace) end. @@ -524,11 +525,11 @@ set_permissions(Username, VirtualHost, ConfigurePerm, WritePerm, ReadPerm, Actin (rabbit_types:username(), rabbit_types:vhost(), rabbit_types:username()) -> 'ok'. clear_permissions(Username, VirtualHost, ActingUser) -> - rabbit_log:debug("Asked to clear permissions for user '~ts' in virtual host '~ts'", + ?LOG_DEBUG("Asked to clear permissions for user '~ts' in virtual host '~ts'", [Username, VirtualHost]), try R = rabbit_db_user:clear_user_permissions(Username, VirtualHost), - rabbit_log:info("Successfully cleared permissions for user '~ts' in virtual host '~ts'", + ?LOG_INFO("Successfully cleared permissions for user '~ts' in virtual host '~ts'", [Username, VirtualHost]), rabbit_event:notify(permission_deleted, [{user, Username}, {vhost, VirtualHost}, @@ -536,7 +537,7 @@ clear_permissions(Username, VirtualHost, ActingUser) -> R catch Class:Error:Stacktrace -> - rabbit_log:warning("Failed to clear permissions for user '~ts' in virtual host '~ts': ~tp", + ?LOG_WARNING("Failed to clear permissions for user '~ts' in virtual host '~ts': ~tp", [Username, VirtualHost, Error]), erlang:raise(Class, Error, Stacktrace) end. @@ -577,7 +578,7 @@ set_permissions_globally(Username, ConfigurePerm, WritePerm, ReadPerm, ActingUse ok. set_topic_permissions(Username, VirtualHost, Exchange, WritePerm, ReadPerm, ActingUser) -> - rabbit_log:debug("Asked to set topic permissions on exchange '~ts' for " + ?LOG_DEBUG("Asked to set topic permissions on exchange '~ts' for " "user '~ts' in virtual host '~ts' to '~ts', '~ts'", [Exchange, Username, VirtualHost, WritePerm, ReadPerm]), WritePermRegex = rabbit_data_coercion:to_binary(WritePerm), @@ -587,7 +588,7 @@ set_topic_permissions(Username, VirtualHost, Exchange, WritePerm, ReadPerm, Acti case re:compile(RegexpBin) of {ok, _} -> ok; {error, Reason} -> - rabbit_log:warning("Failed to set topic permissions on exchange '~ts' for user " + ?LOG_WARNING("Failed to set topic permissions on exchange '~ts' for user " "'~ts' in virtual host '~ts': regular expression '~ts' is invalid", [Exchange, Username, VirtualHost, RegexpBin]), throw({error, {invalid_regexp, RegexpBin, Reason}}) @@ -607,7 +608,7 @@ set_topic_permissions(Username, VirtualHost, Exchange, WritePerm, ReadPerm, Acti } }, R = rabbit_db_user:set_topic_permissions(TopicPermission), - rabbit_log:info("Successfully set topic permissions on exchange '~ts' for " + ?LOG_INFO("Successfully set topic permissions on exchange '~ts' for " "user '~ts' in virtual host '~ts' to '~ts', '~ts'", [Exchange, Username, VirtualHost, WritePerm, ReadPerm]), rabbit_event:notify(topic_permission_created, [ @@ -620,25 +621,25 @@ set_topic_permissions(Username, VirtualHost, Exchange, WritePerm, ReadPerm, Acti R catch throw:{error, {no_such_vhost, _}} = Error -> - rabbit_log:warning("Failed to set topic permissions on exchange '~ts' for user '~ts': virtual host '~ts' does not exist.", + ?LOG_WARNING("Failed to set topic permissions on exchange '~ts' for user '~ts': virtual host '~ts' does not exist.", [Exchange, Username, VirtualHost]), throw(Error); throw:{error, {no_such_user, _}} = Error -> - rabbit_log:warning("Failed to set topic permissions on exchange '~ts' for user '~ts': the user does not exist.", + ?LOG_WARNING("Failed to set topic permissions on exchange '~ts' for user '~ts': the user does not exist.", [Exchange, Username]), throw(Error); Class:Error:Stacktrace -> - rabbit_log:warning("Failed to set topic permissions on exchange '~ts' for user '~ts' in virtual host '~ts': ~tp.", + ?LOG_WARNING("Failed to set topic permissions on exchange '~ts' for user '~ts' in virtual host '~ts': ~tp.", [Exchange, Username, VirtualHost, Error]), erlang:raise(Class, Error, Stacktrace) end . clear_topic_permissions(Username, VirtualHost, ActingUser) -> - rabbit_log:debug("Asked to clear topic permissions for user '~ts' in virtual host '~ts'", + ?LOG_DEBUG("Asked to clear topic permissions for user '~ts' in virtual host '~ts'", [Username, VirtualHost]), try R = rabbit_db_user:clear_topic_permissions(Username, VirtualHost, '_'), - rabbit_log:info("Successfully cleared topic permissions for user '~ts' in virtual host '~ts'", + ?LOG_INFO("Successfully cleared topic permissions for user '~ts' in virtual host '~ts'", [Username, VirtualHost]), rabbit_event:notify(topic_permission_deleted, [{user, Username}, {vhost, VirtualHost}, @@ -646,18 +647,18 @@ clear_topic_permissions(Username, VirtualHost, ActingUser) -> R catch Class:Error:Stacktrace -> - rabbit_log:warning("Failed to clear topic permissions for user '~ts' in virtual host '~ts': ~tp", + ?LOG_WARNING("Failed to clear topic permissions for user '~ts' in virtual host '~ts': ~tp", [Username, VirtualHost, Error]), erlang:raise(Class, Error, Stacktrace) end. clear_topic_permissions(Username, VirtualHost, Exchange, ActingUser) -> - rabbit_log:debug("Asked to clear topic permissions on exchange '~ts' for user '~ts' in virtual host '~ts'", + ?LOG_DEBUG("Asked to clear topic permissions on exchange '~ts' for user '~ts' in virtual host '~ts'", [Exchange, Username, VirtualHost]), try R = rabbit_db_user:clear_topic_permissions( Username, VirtualHost, Exchange), - rabbit_log:info("Successfully cleared topic permissions on exchange '~ts' for user '~ts' in virtual host '~ts'", + ?LOG_INFO("Successfully cleared topic permissions on exchange '~ts' for user '~ts' in virtual host '~ts'", [Exchange, Username, VirtualHost]), rabbit_event:notify(topic_permission_deleted, [{user, Username}, {vhost, VirtualHost}, @@ -665,7 +666,7 @@ clear_topic_permissions(Username, VirtualHost, Exchange, ActingUser) -> R catch Class:Error:Stacktrace -> - rabbit_log:warning("Failed to clear topic permissions on exchange '~ts' for user '~ts' in virtual host '~ts': ~tp", + ?LOG_WARNING("Failed to clear topic permissions on exchange '~ts' for user '~ts' in virtual host '~ts': ~tp", [Exchange, Username, VirtualHost, Error]), erlang:raise(Class, Error, Stacktrace) end. diff --git a/deps/rabbit/src/rabbit_autoheal.erl b/deps/rabbit/src/rabbit_autoheal.erl index 018fb83a8569..fae3eb9ff2c0 100644 --- a/deps/rabbit/src/rabbit_autoheal.erl +++ b/deps/rabbit/src/rabbit_autoheal.erl @@ -7,6 +7,9 @@ -module(rabbit_autoheal). +-include_lib("kernel/include/logger.hrl"). + + -export([init/0, enabled/0, maybe_start/1, rabbit_down/2, node_down/2, handle_msg/3, process_down/2]). @@ -117,7 +120,7 @@ init() -> ok = application:unset_env(rabbit, ?AUTOHEAL_STATE_AFTER_RESTART), case State of {leader_waiting, Winner, _} -> - rabbit_log:info( + ?LOG_INFO( "Autoheal: in progress, requesting report from ~tp", [Winner]), _ = send(Winner, report_autoheal_status), ok; @@ -130,7 +133,7 @@ maybe_start(not_healing) -> case enabled() of true -> Leader = leader(), _ = send(Leader, {request_start, node()}), - rabbit_log:info("Autoheal request sent to ~tp", [Leader]), + ?LOG_INFO("Autoheal request sent to ~tp", [Leader]), not_healing; false -> not_healing end; @@ -151,7 +154,7 @@ leader() -> %% This is the winner receiving its last notification that a node has %% stopped - all nodes can now start again rabbit_down(Node, {winner_waiting, [Node], Notify}) -> - rabbit_log:info("Autoheal: final node has stopped, starting...",[]), + ?LOG_INFO("Autoheal: final node has stopped, starting...",[]), winner_finish(Notify); rabbit_down(Node, {winner_waiting, WaitFor, Notify}) -> @@ -174,24 +177,24 @@ node_down(Node, {winner_waiting, _, Notify}) -> node_down(Node, {leader_waiting, Node, _Notify}) -> %% The winner went down, we don't know what to do so we simply abort. - rabbit_log:info("Autoheal: aborting - winner ~tp went down", [Node]), + ?LOG_INFO("Autoheal: aborting - winner ~tp went down", [Node]), not_healing; node_down(Node, {leader_waiting, _, _} = St) -> %% If it is a partial partition, the winner might continue with the %% healing process. If it is a full partition, the winner will also %% see it and abort. Let's wait for it. - rabbit_log:info("Autoheal: ~tp went down, waiting for winner decision ", [Node]), + ?LOG_INFO("Autoheal: ~tp went down, waiting for winner decision ", [Node]), St; node_down(Node, _State) -> - rabbit_log:info("Autoheal: aborting - ~tp went down", [Node]), + ?LOG_INFO("Autoheal: aborting - ~tp went down", [Node]), not_healing. %% If the process that has to restart the node crashes for an unexpected reason, %% we go back to a not healing state so the node is able to recover. process_down({'EXIT', Pid, Reason}, {restarting, Pid}) when Reason =/= normal -> - rabbit_log:info("Autoheal: aborting - the process responsible for restarting the " + ?LOG_INFO("Autoheal: aborting - the process responsible for restarting the " "node terminated with reason: ~tp", [Reason]), not_healing; @@ -204,14 +207,14 @@ handle_msg({request_start, _Node}, not_healing, []) -> not_healing; handle_msg({request_start, Node}, not_healing, Partitions) -> - rabbit_log:info("Autoheal request received from ~tp", [Node]), + ?LOG_INFO("Autoheal request received from ~tp", [Node]), case check_other_nodes(Partitions) of {error, E} -> - rabbit_log:info("Autoheal request denied: ~ts", [fmt_error(E)]), + ?LOG_INFO("Autoheal request denied: ~ts", [fmt_error(E)]), not_healing; {ok, AllPartitions} -> {Winner, Losers} = make_decision(AllPartitions), - rabbit_log:info("Autoheal decision~n" + ?LOG_INFO("Autoheal decision~n" " * Partitions: ~tp~n" " * Winner: ~tp~n" " * Losers: ~tp", @@ -226,13 +229,13 @@ handle_msg({request_start, Node}, handle_msg({request_start, Node}, State, _Partitions) -> - rabbit_log:info("Autoheal request received from ~tp when healing; " + ?LOG_INFO("Autoheal request received from ~tp when healing; " "ignoring", [Node]), State; handle_msg({become_winner, Losers}, not_healing, _Partitions) -> - rabbit_log:info("Autoheal: I am the winner, waiting for ~tp to stop", + ?LOG_INFO("Autoheal: I am the winner, waiting for ~tp to stop", [Losers]), stop_partition(Losers); @@ -240,7 +243,7 @@ handle_msg({become_winner, Losers}, {winner_waiting, _, Losers}, _Partitions) -> %% The leader has aborted the healing, might have seen us down but %% we didn't see the same. Let's try again as it is the same partition. - rabbit_log:info("Autoheal: I am the winner and received a duplicated " + ?LOG_INFO("Autoheal: I am the winner and received a duplicated " "request, waiting again for ~tp to stop", [Losers]), stop_partition(Losers); @@ -248,7 +251,7 @@ handle_msg({become_winner, _}, {winner_waiting, _, Losers}, _Partitions) -> %% Something has happened to the leader, it might have seen us down but we %% are still alive. Partitions have changed, cannot continue. - rabbit_log:info("Autoheal: I am the winner and received another healing " + ?LOG_INFO("Autoheal: I am the winner and received another healing " "request, partitions have changed to ~tp. Aborting ", [Losers]), winner_finish(Losers), not_healing; @@ -272,7 +275,7 @@ handle_msg({winner_is, Winner}, State = {winner_waiting, _OutstandingStops, _Not handle_msg(Request, {restarting, Pid} = St, _Partitions) -> %% ignore, we can contribute no further - rabbit_log:info("Autoheal: Received the request ~tp while waiting for ~tp " + ?LOG_INFO("Autoheal: Received the request ~tp while waiting for ~tp " "to restart the node. Ignoring it ", [Request, Pid]), St; @@ -295,21 +298,21 @@ handle_msg({autoheal_finished, Winner}, %% The winner is finished with the autoheal process and notified us %% (the leader). We can transition to the "not_healing" state and %% accept new requests. - rabbit_log:info("Autoheal finished according to winner ~tp", [Winner]), + ?LOG_INFO("Autoheal finished according to winner ~tp", [Winner]), not_healing; handle_msg({autoheal_finished, Winner}, not_healing, _Partitions) when Winner =:= node() -> %% We are the leader and the winner. The state already transitioned %% to "not_healing" at the end of the autoheal process. - rabbit_log:info("Autoheal finished according to winner ~tp", [node()]), + ?LOG_INFO("Autoheal finished according to winner ~tp", [node()]), not_healing; handle_msg({autoheal_finished, Winner}, not_healing, _Partitions) -> %% We might have seen the winner down during a partial partition and %% transitioned to not_healing. However, the winner was still able %% to finish. Let it pass. - rabbit_log:info("Autoheal finished according to winner ~tp." + ?LOG_INFO("Autoheal finished according to winner ~tp." " Unexpected, I might have previously seen the winner down", [Winner]), not_healing. @@ -318,7 +321,7 @@ handle_msg({autoheal_finished, Winner}, not_healing, _Partitions) -> send(Node, Msg) -> {?SERVER, Node} ! {autoheal_msg, Msg}. abort(Down, Notify) -> - rabbit_log:info("Autoheal: aborting - ~tp down", [Down]), + ?LOG_INFO("Autoheal: aborting - ~tp down", [Down]), %% Make sure any nodes waiting for us start - it won't necessarily %% heal the partition but at least they won't get stuck. %% If we are executing this, we are not stopping. Thus, don't wait @@ -362,7 +365,7 @@ wait_for_supervisors(Monitors) -> after 60000 -> AliveLosers = [Node || {_, Node} <- pmon:monitored(Monitors)], - rabbit_log:info("Autoheal: mnesia in nodes ~tp is still up, sending " + ?LOG_INFO("Autoheal: mnesia in nodes ~tp is still up, sending " "winner notification again to these ", [AliveLosers]), _ = [send(L, {winner_is, node()}) || L <- AliveLosers], wait_for_mnesia_shutdown(AliveLosers) @@ -370,7 +373,7 @@ wait_for_supervisors(Monitors) -> end. restart_loser(State, Winner) -> - rabbit_log:warning("Autoheal: we were selected to restart; winner is ~tp", [Winner]), + ?LOG_WARNING("Autoheal: we were selected to restart; winner is ~tp", [Winner]), NextStateTimeout = application:get_env(rabbit, autoheal_state_transition_timeout, 60000), rabbit_node_monitor:run_outside_applications( fun () -> @@ -382,7 +385,7 @@ restart_loser(State, Winner) -> autoheal_safe_to_start -> State after NextStateTimeout -> - rabbit_log:warning( + ?LOG_WARNING( "Autoheal: timed out waiting for a safe-to-start message from the winner (~tp); will retry", [Winner]), not_healing diff --git a/deps/rabbit/src/rabbit_binding.erl b/deps/rabbit/src/rabbit_binding.erl index dc322aa38dc1..ed03952d2bb2 100644 --- a/deps/rabbit/src/rabbit_binding.erl +++ b/deps/rabbit/src/rabbit_binding.erl @@ -8,6 +8,7 @@ -module(rabbit_binding). -include_lib("rabbit_common/include/rabbit.hrl"). -include("amqqueue.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([recover/0, recover/2, exists/1, add/2, add/3, remove/2, remove/3]). -export([list/1, list_for_source/1, list_for_destination/1, @@ -117,7 +118,7 @@ recover_semi_durable_route(Gatherer, Binding, Src, Dst, ToRecover, Fun) -> gatherer:finish(Gatherer) end); {error, not_found}=Error -> - rabbit_log:warning( + ?LOG_WARNING( "expected exchange ~tp to exist during recovery, " "error: ~tp", [Src, Error]), ok diff --git a/deps/rabbit/src/rabbit_boot_steps.erl b/deps/rabbit/src/rabbit_boot_steps.erl index e4116ffa886e..f62da5e6097a 100644 --- a/deps/rabbit/src/rabbit_boot_steps.erl +++ b/deps/rabbit/src/rabbit_boot_steps.erl @@ -20,7 +20,7 @@ run_boot_steps() -> run_boot_steps(Apps) -> [begin - rabbit_log:info("Running boot step ~ts defined by app ~ts", [Step, App]), + ?LOG_INFO("Running boot step ~ts defined by app ~ts", [Step, App]), ok = run_step(Attrs, mfa) end || {App, Step, Attrs} <- find_steps(Apps)], ok. @@ -48,11 +48,11 @@ find_steps(Apps) -> run_step(Attributes, AttributeName) -> [begin - rabbit_log:debug("Applying MFA: M = ~ts, F = ~ts, A = ~tp", + ?LOG_DEBUG("Applying MFA: M = ~ts, F = ~ts, A = ~tp", [M, F, A]), case apply(M,F,A) of ok -> - rabbit_log:debug("Finished MFA: M = ~ts, F = ~ts, A = ~tp", + ?LOG_DEBUG("Finished MFA: M = ~ts, F = ~ts, A = ~tp", [M, F, A]); {error, Reason} -> exit({error, Reason}) end diff --git a/deps/rabbit/src/rabbit_channel.erl b/deps/rabbit/src/rabbit_channel.erl index 22cd1b500103..0e6a2a74d221 100644 --- a/deps/rabbit/src/rabbit_channel.erl +++ b/deps/rabbit/src/rabbit_channel.erl @@ -360,7 +360,7 @@ info(Pid) -> end catch exit:{timeout, _} -> - rabbit_log:error("Timed out getting channel ~tp info", [Pid]), + ?LOG_ERROR("Timed out getting channel ~tp info", [Pid]), throw(timeout) end. @@ -375,7 +375,7 @@ info(Pid, Items) -> end catch exit:{timeout, _} -> - rabbit_log:error("Timed out getting channel ~tp info", [Pid]), + ?LOG_ERROR("Timed out getting channel ~tp info", [Pid]), throw(timeout) end. @@ -411,7 +411,7 @@ refresh_config_local() -> try gen_server2:call(C, refresh_config, infinity) catch _:Reason -> - rabbit_log:error("Failed to refresh channel config " + ?LOG_ERROR("Failed to refresh channel config " "for channel ~tp. Reason ~tp", [C, Reason]) end @@ -425,7 +425,7 @@ refresh_interceptors() -> try gen_server2:call(C, refresh_interceptors, ?REFRESH_TIMEOUT) catch _:Reason -> - rabbit_log:error("Failed to refresh channel interceptors " + ?LOG_ERROR("Failed to refresh channel interceptors " "for channel ~tp. Reason ~tp", [C, Reason]) end @@ -643,7 +643,7 @@ handle_cast(terminate, State = #ch{cfg = #conf{writer_pid = WriterPid}}) -> ok = rabbit_writer:flush(WriterPid) catch _Class:Reason -> - rabbit_log:debug("Failed to flush pending writes on a terminating connection, reason: ~tp", [Reason]) + ?LOG_DEBUG("Failed to flush pending writes on a terminating connection, reason: ~tp", [Reason]) end, {stop, normal, State}; @@ -805,7 +805,7 @@ terminate(_Reason, case rabbit_confirms:size(State#ch.unconfirmed) of 0 -> ok; NumConfirms -> - rabbit_log:warning("Channel is stopping with ~b pending publisher confirms", + ?LOG_WARNING("Channel is stopping with ~b pending publisher confirms", [NumConfirms]) end. diff --git a/deps/rabbit/src/rabbit_channel_tracking.erl b/deps/rabbit/src/rabbit_channel_tracking.erl index 5904f48e13d3..63595452d3cd 100644 --- a/deps/rabbit/src/rabbit_channel_tracking.erl +++ b/deps/rabbit/src/rabbit_channel_tracking.erl @@ -34,6 +34,7 @@ -export([count_local_tracked_items_of_user/1]). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -import(rabbit_misc, [pget/2]). @@ -214,13 +215,13 @@ ensure_tracked_tables_for_this_node() -> %% Create tables ensure_tracked_channels_table_for_this_node() -> - rabbit_log:info("Setting up a table for channel tracking on this node: ~tp", + ?LOG_INFO("Setting up a table for channel tracking on this node: ~tp", [?TRACKED_CHANNEL_TABLE]), ets:new(?TRACKED_CHANNEL_TABLE, [named_table, public, {write_concurrency, true}, {keypos, #tracked_channel.pid}]). ensure_per_user_tracked_channels_table_for_this_node() -> - rabbit_log:info("Setting up a table for channel tracking on this node: ~tp", + ?LOG_INFO("Setting up a table for channel tracking on this node: ~tp", [?TRACKED_CHANNEL_TABLE_PER_USER]), ets:new(?TRACKED_CHANNEL_TABLE_PER_USER, [named_table, public, {write_concurrency, true}]). diff --git a/deps/rabbit/src/rabbit_classic_queue.erl b/deps/rabbit/src/rabbit_classic_queue.erl index 3a0d72863245..a00bea79d466 100644 --- a/deps/rabbit/src/rabbit_classic_queue.erl +++ b/deps/rabbit/src/rabbit_classic_queue.erl @@ -4,6 +4,7 @@ -include("amqqueue.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). %% TODO possible to use sets / maps instead of lists? %% Check performance with QoS 1 and 1 million target queues. @@ -177,13 +178,13 @@ delete(Q0, IfUnused, IfEmpty, ActingUser) when ?amqqueue_is_classic(Q0) -> #resource{name = Name, virtual_host = Vhost} = QName, case IfEmpty of true -> - rabbit_log:error("Queue ~ts in vhost ~ts is down. " + ?LOG_ERROR("Queue ~ts in vhost ~ts is down. " "The queue may be non-empty. " "Refusing to force-delete.", [Name, Vhost]), {error, not_empty}; false -> - rabbit_log:warning("Queue ~ts in vhost ~ts is down. " + ?LOG_WARNING("Queue ~ts in vhost ~ts is down. " "Forcing queue deletion.", [Name, Vhost]), case delete_crashed_internal(Q, ActingUser) of @@ -219,7 +220,7 @@ recover(VHost, Queues) -> FailedQs = find_missing_queues(Queues,RecoveredQs), {RecoveredQs, FailedQs}; {error, Reason} -> - rabbit_log:error("Failed to start queue supervisor for vhost '~ts': ~ts", [VHost, Reason]), + ?LOG_ERROR("Failed to start queue supervisor for vhost '~ts': ~ts", [VHost, Reason]), throw({error, Reason}) end. @@ -588,7 +589,7 @@ recover_durable_queues(QueuesAndRecoveryTerms) -> gen_server2:mcall( [{rabbit_amqqueue_sup_sup:start_queue_process(node(), Q), {init, {self(), Terms}}} || {Q, Terms} <- QueuesAndRecoveryTerms]), - [rabbit_log:error("Queue ~tp failed to initialise: ~tp", + [?LOG_ERROR("Queue ~tp failed to initialise: ~tp", [Pid, Error]) || {Pid, Error} <- Failures], [Q || {_, {new, Q}} <- Results]. diff --git a/deps/rabbit/src/rabbit_classic_queue_index_v2.erl b/deps/rabbit/src/rabbit_classic_queue_index_v2.erl index c0c812abf99c..cc776526d613 100644 --- a/deps/rabbit/src/rabbit_classic_queue_index_v2.erl +++ b/deps/rabbit/src/rabbit_classic_queue_index_v2.erl @@ -42,6 +42,7 @@ -define(ENTRY_SIZE, 32). %% bytes -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). %% Set to true to get an awful lot of debug logs. -if(false). -define(DEBUG(X,Y), logger:debug("~0p: " ++ X, [?FUNCTION_NAME|Y])). @@ -255,7 +256,7 @@ recover(#resource{ virtual_host = VHost, name = QueueName } = Name, Terms, State = recover_segments(State0, Terms, IsMsgStoreClean, ContainsCheckFun, OnSyncFun, OnSyncMsgFun, CountersRef, Context), - rabbit_log:warning("Queue ~ts in vhost ~ts dropped ~b/~b/~b persistent messages " + ?LOG_WARNING("Queue ~ts in vhost ~ts dropped ~b/~b/~b persistent messages " "and ~b transient messages after unclean shutdown", [QueueName, VHost, counters:get(CountersRef, ?RECOVER_DROPPED_PERSISTENT_PER_VHOST), @@ -329,7 +330,7 @@ recover_segments(State0, ContainsCheckFun, StoreState0, CountersRef, [Segment|Ta %% File was either empty or the header was invalid. %% We cannot recover this file. _ -> - rabbit_log:warning("Deleting invalid v2 segment file ~ts (file has invalid header)", + ?LOG_WARNING("Deleting invalid v2 segment file ~ts (file has invalid header)", [SegmentFile]), ok = file:close(Fd), _ = prim_file:delete(SegmentFile), @@ -436,7 +437,7 @@ recover_segment(State, ContainsCheckFun, StoreState0, CountersRef, Fd, recover_index_v1_clean(State0 = #qi{ queue_name = Name }, Terms, IsMsgStoreClean, ContainsCheckFun, OnSyncFun, OnSyncMsgFun) -> #resource{virtual_host = VHost, name = QName} = Name, - rabbit_log:info("Converting queue ~ts in vhost ~ts from v1 to v2 after clean shutdown", [QName, VHost]), + ?LOG_INFO("Converting queue ~ts in vhost ~ts from v1 to v2 after clean shutdown", [QName, VHost]), {_, _, V1State} = rabbit_queue_index:recover(Name, Terms, IsMsgStoreClean, ContainsCheckFun, OnSyncFun, OnSyncMsgFun, convert), @@ -445,7 +446,7 @@ recover_index_v1_clean(State0 = #qi{ queue_name = Name }, Terms, IsMsgStoreClean %% share code with dirty recovery. CountersRef = counters:new(?RECOVER_COUNTER_SIZE, []), State = recover_index_v1_common(State0, V1State, CountersRef), - rabbit_log:info("Queue ~ts in vhost ~ts converted ~b total messages from v1 to v2", + ?LOG_INFO("Queue ~ts in vhost ~ts converted ~b total messages from v1 to v2", [QName, VHost, counters:get(CountersRef, ?RECOVER_COUNT)]), State. @@ -453,7 +454,7 @@ recover_index_v1_dirty(State0 = #qi{ queue_name = Name }, Terms, IsMsgStoreClean ContainsCheckFun, OnSyncFun, OnSyncMsgFun, CountersRef) -> #resource{virtual_host = VHost, name = QName} = Name, - rabbit_log:info("Converting queue ~ts in vhost ~ts from v1 to v2 after unclean shutdown", [QName, VHost]), + ?LOG_INFO("Converting queue ~ts in vhost ~ts from v1 to v2 after unclean shutdown", [QName, VHost]), %% We ignore the count and bytes returned here because we cannot trust %% rabbit_queue_index: it has a bug that may lead to more bytes being %% returned than it really has. @@ -464,7 +465,7 @@ recover_index_v1_dirty(State0 = #qi{ queue_name = Name }, Terms, IsMsgStoreClean ContainsCheckFun, OnSyncFun, OnSyncMsgFun, convert), State = recover_index_v1_common(State0, V1State, CountersRef), - rabbit_log:info("Queue ~ts in vhost ~ts converted ~b total messages from v1 to v2", + ?LOG_INFO("Queue ~ts in vhost ~ts converted ~b total messages from v1 to v2", [QName, VHost, counters:get(CountersRef, ?RECOVER_COUNT)]), State. diff --git a/deps/rabbit/src/rabbit_classic_queue_store_v2.erl b/deps/rabbit/src/rabbit_classic_queue_store_v2.erl index d3286da45532..fb89bca6a667 100644 --- a/deps/rabbit/src/rabbit_classic_queue_store_v2.erl +++ b/deps/rabbit/src/rabbit_classic_queue_store_v2.erl @@ -56,6 +56,7 @@ -define(ENTRY_HEADER_SIZE, 8). %% bytes -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). %% Set to true to get an awful lot of debug logs. -if(false). @@ -317,7 +318,7 @@ read_from_disk(SeqId, {?MODULE, Offset, Size}, State0) -> CRC32Expected = <>, ok catch C:E:S -> - rabbit_log:error("Per-queue store CRC32 check failed in ~ts seq id ~b offset ~b size ~b", + ?LOG_ERROR("Per-queue store CRC32 check failed in ~ts seq id ~b offset ~b size ~b", [segment_file(Segment, State), SeqId, Offset, Size]), erlang:raise(C, E, S) end @@ -415,7 +416,7 @@ parse_many_from_disk([<>, ok catch C:E:S -> - rabbit_log:error("Per-queue store CRC32 check failed in ~ts", + ?LOG_ERROR("Per-queue store CRC32 check failed in ~ts", [segment_file(Segment, State)]), erlang:raise(C, E, S) end diff --git a/deps/rabbit/src/rabbit_connection_tracking.erl b/deps/rabbit/src/rabbit_connection_tracking.erl index 481fe44627ea..1716742432eb 100644 --- a/deps/rabbit/src/rabbit_connection_tracking.erl +++ b/deps/rabbit/src/rabbit_connection_tracking.erl @@ -41,6 +41,7 @@ count_local_tracked_items_of_user/1]). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -import(rabbit_misc, [pget/2]). @@ -189,17 +190,17 @@ ensure_tracked_tables_for_this_node() -> ensure_tracked_connections_table_for_this_node() -> _ = ets:new(?TRACKED_CONNECTION_TABLE, [named_table, public, {write_concurrency, true}, {keypos, #tracked_connection.id}]), - rabbit_log:info("Setting up a table for connection tracking on this node: ~tp", + ?LOG_INFO("Setting up a table for connection tracking on this node: ~tp", [?TRACKED_CONNECTION_TABLE]). ensure_per_vhost_tracked_connections_table_for_this_node() -> - rabbit_log:info("Setting up a table for per-vhost connection counting on this node: ~tp", + ?LOG_INFO("Setting up a table for per-vhost connection counting on this node: ~tp", [?TRACKED_CONNECTION_TABLE_PER_VHOST]), ets:new(?TRACKED_CONNECTION_TABLE_PER_VHOST, [named_table, public, {write_concurrency, true}]). ensure_per_user_tracked_connections_table_for_this_node() -> _ = ets:new(?TRACKED_CONNECTION_TABLE_PER_USER, [named_table, public, {write_concurrency, true}]), - rabbit_log:info("Setting up a table for per-user connection counting on this node: ~tp", + ?LOG_INFO("Setting up a table for per-user connection counting on this node: ~tp", [?TRACKED_CONNECTION_TABLE_PER_USER]). -spec tracked_connection_table_name_for(node()) -> atom(). @@ -420,7 +421,7 @@ close_connection(#tracked_connection{pid = Pid, type = network}, Message) -> ok; _:Err -> %% ignore, don't terminate - rabbit_log:warning("Could not close connection ~tp: ~tp", [Pid, Err]), + ?LOG_WARNING("Could not close connection ~tp: ~tp", [Pid, Err]), ok end; close_connection(#tracked_connection{pid = Pid, type = direct}, Message) -> diff --git a/deps/rabbit/src/rabbit_db_cluster.erl b/deps/rabbit/src/rabbit_db_cluster.erl index e13c2f01307e..aab25f5373fd 100644 --- a/deps/rabbit/src/rabbit_db_cluster.erl +++ b/deps/rabbit/src/rabbit_db_cluster.erl @@ -223,7 +223,7 @@ join(RemoteNode, NodeType) %% as RemoteNode thinks this node is already in the cluster. %% Attempt to leave the RemoteNode cluster, the discovery cluster, %% and simply retry the operation. - rabbit_log:info("Mnesia: node ~tp thinks it's clustered " + ?LOG_INFO("Mnesia: node ~tp thinks it's clustered " "with node ~tp, but ~tp disagrees. ~tp will ask " "to leave the cluster and try again.", [RemoteNode, node(), node(), node()]), diff --git a/deps/rabbit/src/rabbit_db_msup.erl b/deps/rabbit/src/rabbit_db_msup.erl index 7ab072bf2b4c..9d9517999ed3 100644 --- a/deps/rabbit/src/rabbit_db_msup.erl +++ b/deps/rabbit/src/rabbit_db_msup.erl @@ -11,6 +11,7 @@ -include("mirrored_supervisor.hrl"). -include("include/rabbit_khepri.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([ create_tables/0, @@ -96,7 +97,7 @@ create_or_update_in_mnesia(Group, Overall, Delegate, ChildSpec, Id) -> rabbit_mnesia:execute_mnesia_transaction( fun() -> ReadResult = mnesia:wread({?TABLE, {Group, Id}}), - rabbit_log:debug("Mirrored supervisor: check_start table ~ts read for key ~tp returned ~tp", + ?LOG_DEBUG("Mirrored supervisor: check_start table ~ts read for key ~tp returned ~tp", [?TABLE, {Group, Id}, ReadResult]), case ReadResult of [] -> _ = write_in_mnesia(Group, Overall, ChildSpec, Id), @@ -105,12 +106,12 @@ create_or_update_in_mnesia(Group, Overall, Delegate, ChildSpec, Id) -> mirroring_pid = Pid} = S, case Overall of Pid -> - rabbit_log:debug("Mirrored supervisor: overall matched mirrored pid ~tp", [Pid]), + ?LOG_DEBUG("Mirrored supervisor: overall matched mirrored pid ~tp", [Pid]), Delegate; _ -> - rabbit_log:debug("Mirrored supervisor: overall ~tp did not match mirrored pid ~tp", [Overall, Pid]), + ?LOG_DEBUG("Mirrored supervisor: overall ~tp did not match mirrored pid ~tp", [Overall, Pid]), Sup = mirrored_supervisor:supervisor(Pid), - rabbit_log:debug("Mirrored supervisor: supervisor(~tp) returned ~tp", [Pid, Sup]), + ?LOG_DEBUG("Mirrored supervisor: supervisor(~tp) returned ~tp", [Pid, Sup]), case Sup of dead -> _ = write_in_mnesia(Group, Overall, ChildSpec, Id), diff --git a/deps/rabbit/src/rabbit_db_queue.erl b/deps/rabbit/src/rabbit_db_queue.erl index 281cd0de3714..304b597985b0 100644 --- a/deps/rabbit/src/rabbit_db_queue.erl +++ b/deps/rabbit/src/rabbit_db_queue.erl @@ -14,6 +14,7 @@ -include("amqqueue.hrl"). -include("include/rabbit_khepri.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([ get/1, @@ -341,7 +342,7 @@ count(VHostName) -> try list_for_count(VHostName) catch _:Err -> - rabbit_log:error("Failed to fetch number of queues in vhost ~p:~n~p", + ?LOG_ERROR("Failed to fetch number of queues in vhost ~p:~n~p", [VHostName, Err]), 0 end. diff --git a/deps/rabbit/src/rabbit_db_vhost.erl b/deps/rabbit/src/rabbit_db_vhost.erl index 1584e764a93f..e9697bf5e987 100644 --- a/deps/rabbit/src/rabbit_db_vhost.erl +++ b/deps/rabbit/src/rabbit_db_vhost.erl @@ -13,6 +13,7 @@ -include("include/rabbit_khepri.hrl"). -include("vhost.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([create_or_get/3, merge_metadata/2, @@ -102,7 +103,7 @@ create_or_get_in_mnesia_tx(VHostName, VHost) -> create_or_get_in_khepri(VHostName, VHost) -> Path = khepri_vhost_path(VHostName), - rabbit_log:debug("Inserting a virtual host record ~tp", [VHost]), + ?LOG_DEBUG("Inserting a virtual host record ~tp", [VHost]), case rabbit_khepri:create(Path, VHost) of ok -> {new, VHost}; @@ -137,7 +138,7 @@ merge_metadata(VHostName, Metadata) when is_binary(VHostName) andalso is_map(Metadata) -> case do_merge_metadata(VHostName, Metadata) of {ok, VHost} when ?is_vhost(VHost) -> - rabbit_log:debug("Updated a virtual host record ~tp", [VHost]), + ?LOG_DEBUG("Updated a virtual host record ~tp", [VHost]), {ok, VHost}; {error, _} = Error -> Error @@ -169,7 +170,7 @@ merge_metadata_in_khepri(VHostName, Metadata) -> case Ret1 of {ok, #{Path := #{data := VHost0, payload_version := DVersion}}} -> VHost = vhost:merge_metadata(VHost0, Metadata), - rabbit_log:debug("Updating a virtual host record ~p", [VHost]), + ?LOG_DEBUG("Updating a virtual host record ~p", [VHost]), Path1 = khepri_path:combine_with_conditions( Path, [#if_payload_version{version = DVersion}]), Ret2 = rabbit_khepri:put(Path1, VHost), @@ -240,7 +241,7 @@ enable_protection_from_deletion(VHostName) -> MetadataPatch = #{ protected_from_deletion => true }, - rabbit_log:info("Enabling deletion protection for virtual host '~ts'", [VHostName]), + ?LOG_INFO("Enabling deletion protection for virtual host '~ts'", [VHostName]), merge_metadata(VHostName, MetadataPatch). -spec disable_protection_from_deletion(VHostName) -> Ret when @@ -253,7 +254,7 @@ disable_protection_from_deletion(VHostName) -> MetadataPatch = #{ protected_from_deletion => false }, - rabbit_log:info("Disabling deletion protection for virtual host '~ts'", [VHostName]), + ?LOG_INFO("Disabling deletion protection for virtual host '~ts'", [VHostName]), merge_metadata(VHostName, MetadataPatch). %% ------------------------------------------------------------------- diff --git a/deps/rabbit/src/rabbit_db_vhost_defaults.erl b/deps/rabbit/src/rabbit_db_vhost_defaults.erl index 37bde1b76d5f..952006f703b8 100644 --- a/deps/rabbit/src/rabbit_db_vhost_defaults.erl +++ b/deps/rabbit/src/rabbit_db_vhost_defaults.erl @@ -7,6 +7,9 @@ -module(rabbit_db_vhost_defaults). +-include_lib("kernel/include/logger.hrl"). + + -export([apply/2]). -export([list_limits/1, list_operator_policies/1, list_users/1]). @@ -36,20 +39,20 @@ apply(VHost, ActingUser) -> ok; L -> ok = rabbit_vhost_limit:set(VHost, L, ActingUser), - rabbit_log:info("Applied default limits to vhost '~tp': ~tp", [VHost, L]) + ?LOG_INFO("Applied default limits to vhost '~tp': ~tp", [VHost, L]) end, lists:foreach( fun(P) -> ok = rabbit_policy:set_op(VHost, P#seeding_policy.name, P#seeding_policy.queue_pattern, P#seeding_policy.definition, undefined, undefined, ActingUser), - rabbit_log:info("Applied default operator policy to vhost '~tp': ~tp", [VHost, P]) + ?LOG_INFO("Applied default operator policy to vhost '~tp': ~tp", [VHost, P]) end, list_operator_policies(VHost) ), lists:foreach( fun(U) -> ok = add_user(VHost, U, ActingUser), - rabbit_log:info("Added default user to vhost '~tp': ~tp", [VHost, maps:remove(password, U)]) + ?LOG_INFO("Added default user to vhost '~tp': ~tp", [VHost, maps:remove(password, U)]) end, list_users(VHost) ), diff --git a/deps/rabbit/src/rabbit_dead_letter.erl b/deps/rabbit/src/rabbit_dead_letter.erl index d12541c2d2f1..172bc0bc9306 100644 --- a/deps/rabbit/src/rabbit_dead_letter.erl +++ b/deps/rabbit/src/rabbit_dead_letter.erl @@ -12,6 +12,7 @@ detect_cycles/3]). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). %%---------------------------------------------------------------------------- @@ -74,7 +75,7 @@ log_cycle_once(Cycle) -> true -> ok; undefined -> - rabbit_log:warning( + ?LOG_WARNING( "Message dropped because the following list of queues (ordered by " "death recency) contains a dead letter cycle without reason 'rejected'. " "This list will not be logged again: ~tp", diff --git a/deps/rabbit/src/rabbit_definitions.erl b/deps/rabbit/src/rabbit_definitions.erl index 884466a81787..8e0f7e048467 100644 --- a/deps/rabbit/src/rabbit_definitions.erl +++ b/deps/rabbit/src/rabbit_definitions.erl @@ -30,6 +30,7 @@ %% * rabbit_definitions_hashing -module(rabbit_definitions). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([boot/0]). %% automatic import on boot @@ -177,7 +178,7 @@ validate_definitions(Body) when is_binary(Body) -> -spec import_raw(Body :: binary() | iolist()) -> ok | {error, term()}. import_raw(Body) -> - rabbit_log:info("Asked to import definitions. Acting user: ~ts", [?INTERNAL_USER]), + ?LOG_INFO("Asked to import definitions. Acting user: ~ts", [?INTERNAL_USER]), case decode([], Body) of {error, E} -> {error, E}; {ok, _, Map} -> apply_defs(Map, ?INTERNAL_USER) @@ -185,7 +186,7 @@ import_raw(Body) -> -spec import_raw(Body :: binary() | iolist(), VHost :: vhost:name()) -> ok | {error, term()}. import_raw(Body, VHost) -> - rabbit_log:info("Asked to import definitions. Acting user: ~ts", [?INTERNAL_USER]), + ?LOG_INFO("Asked to import definitions. Acting user: ~ts", [?INTERNAL_USER]), case decode([], Body) of {error, E} -> {error, E}; {ok, _, Map} -> apply_defs(Map, ?INTERNAL_USER, fun() -> ok end, VHost) @@ -195,7 +196,7 @@ import_raw(Body, VHost) -> import_parsed(Body0) when is_list(Body0) -> import_parsed(maps:from_list(Body0)); import_parsed(Body0) when is_map(Body0) -> - rabbit_log:info("Asked to import definitions. Acting user: ~ts", [?INTERNAL_USER]), + ?LOG_INFO("Asked to import definitions. Acting user: ~ts", [?INTERNAL_USER]), Body = atomise_map_keys(Body0), apply_defs(Body, ?INTERNAL_USER). @@ -203,7 +204,7 @@ import_parsed(Body0) when is_map(Body0) -> import_parsed(Body0, VHost) when is_list(Body0) -> import_parsed(maps:from_list(Body0), VHost); import_parsed(Body0, VHost) -> - rabbit_log:info("Asked to import definitions. Acting user: ~ts", [?INTERNAL_USER]), + ?LOG_INFO("Asked to import definitions. Acting user: ~ts", [?INTERNAL_USER]), Body = atomise_map_keys(Body0), apply_defs(Body, ?INTERNAL_USER, fun() -> ok end, VHost). @@ -212,7 +213,7 @@ import_parsed(Body0, VHost) -> import_parsed_with_hashing(Body0) when is_list(Body0) -> import_parsed(maps:from_list(Body0)); import_parsed_with_hashing(Body0) when is_map(Body0) -> - rabbit_log:info("Asked to import definitions. Acting user: ~ts", [?INTERNAL_USER]), + ?LOG_INFO("Asked to import definitions. Acting user: ~ts", [?INTERNAL_USER]), case should_skip_if_unchanged() of false -> import_parsed(Body0); @@ -222,10 +223,10 @@ import_parsed_with_hashing(Body0) when is_map(Body0) -> Algo = rabbit_definitions_hashing:hashing_algorithm(), case rabbit_definitions_hashing:hash(Algo, Body) of PreviousHash -> - rabbit_log:info("Submitted definition content hash matches the stored one: ~ts", [binary:part(rabbit_misc:hexify(PreviousHash), 0, 12)]), + ?LOG_INFO("Submitted definition content hash matches the stored one: ~ts", [binary:part(rabbit_misc:hexify(PreviousHash), 0, 12)]), ok; Other -> - rabbit_log:debug("Submitted definition content hash: ~ts, stored one: ~ts", [ + ?LOG_DEBUG("Submitted definition content hash: ~ts, stored one: ~ts", [ binary:part(rabbit_misc:hexify(PreviousHash), 0, 10), binary:part(rabbit_misc:hexify(Other), 0, 10) ]), @@ -239,7 +240,7 @@ import_parsed_with_hashing(Body0) when is_map(Body0) -> import_parsed_with_hashing(Body0, VHost) when is_list(Body0) -> import_parsed(maps:from_list(Body0), VHost); import_parsed_with_hashing(Body0, VHost) -> - rabbit_log:info("Asked to import definitions for virtual host '~ts'. Acting user: ~ts", [?INTERNAL_USER, VHost]), + ?LOG_INFO("Asked to import definitions for virtual host '~ts'. Acting user: ~ts", [?INTERNAL_USER, VHost]), case should_skip_if_unchanged() of false -> @@ -250,10 +251,10 @@ import_parsed_with_hashing(Body0, VHost) -> Algo = rabbit_definitions_hashing:hashing_algorithm(), case rabbit_definitions_hashing:hash(Algo, Body) of PreviousHash -> - rabbit_log:info("Submitted definition content hash matches the stored one: ~ts", [binary:part(rabbit_misc:hexify(PreviousHash), 0, 12)]), + ?LOG_INFO("Submitted definition content hash matches the stored one: ~ts", [binary:part(rabbit_misc:hexify(PreviousHash), 0, 12)]), ok; Other -> - rabbit_log:debug("Submitted definition content hash: ~ts, stored one: ~ts", [ + ?LOG_DEBUG("Submitted definition content hash: ~ts, stored one: ~ts", [ binary:part(rabbit_misc:hexify(PreviousHash), 0, 10), binary:part(rabbit_misc:hexify(Other), 0, 10) ]), @@ -340,14 +341,14 @@ maybe_load_definitions_from_local_filesystem(App, Key) -> undefined -> ok; {ok, none} -> ok; {ok, Path} -> - rabbit_log:debug("~ts.~ts is set to '~ts', will discover definition file(s) to import", [App, Key, Path]), + ?LOG_DEBUG("~ts.~ts is set to '~ts', will discover definition file(s) to import", [App, Key, Path]), IsDir = filelib:is_dir(Path), Mod = rabbit_definitions_import_local_filesystem, - rabbit_log:debug("Will use module ~ts to import definitions", [Mod]), + ?LOG_DEBUG("Will use module ~ts to import definitions", [Mod]), case should_skip_if_unchanged() of false -> - rabbit_log:debug("Will re-import definitions even if they have not changed"), + ?LOG_DEBUG("Will re-import definitions even if they have not changed"), Mod:load(IsDir, Path); true -> maybe_load_definitions_from_local_filesystem_if_unchanged(Mod, IsDir, Path) @@ -356,16 +357,16 @@ maybe_load_definitions_from_local_filesystem(App, Key) -> maybe_load_definitions_from_local_filesystem_if_unchanged(Mod, IsDir, Path) -> Algo = rabbit_definitions_hashing:hashing_algorithm(), - rabbit_log:debug("Will import definitions only if definition file/directory has changed, hashing algo: ~ts", [Algo]), + ?LOG_DEBUG("Will import definitions only if definition file/directory has changed, hashing algo: ~ts", [Algo]), CurrentHash = rabbit_definitions_hashing:stored_global_hash(), - rabbit_log:debug("Previously stored hash value of imported definitions: ~ts...", [binary:part(rabbit_misc:hexify(CurrentHash), 0, 12)]), + ?LOG_DEBUG("Previously stored hash value of imported definitions: ~ts...", [binary:part(rabbit_misc:hexify(CurrentHash), 0, 12)]), case Mod:load_with_hashing(IsDir, Path, CurrentHash, Algo) of {error, Err} -> {error, Err}; CurrentHash -> - rabbit_log:info("Hash value of imported definitions matches current contents"); + ?LOG_INFO("Hash value of imported definitions matches current contents"); UpdatedHash -> - rabbit_log:debug("Hash value of imported definitions has changed to ~ts", [binary:part(rabbit_misc:hexify(UpdatedHash), 0, 12)]), + ?LOG_DEBUG("Hash value of imported definitions has changed to ~ts", [binary:part(rabbit_misc:hexify(UpdatedHash), 0, 12)]), rabbit_definitions_hashing:store_global_hash(UpdatedHash) end. @@ -387,20 +388,20 @@ maybe_load_definitions_from_pluggable_source(App, Key) -> maybe_load_definitions_from_pluggable_source_if_unchanged(Mod, Proplist) -> case should_skip_if_unchanged() of false -> - rabbit_log:debug("Will use module ~ts to import definitions", [Mod]), + ?LOG_DEBUG("Will use module ~ts to import definitions", [Mod]), Mod:load(Proplist); true -> - rabbit_log:debug("Will use module ~ts to import definitions (if definition file/directory/source has changed)", [Mod]), + ?LOG_DEBUG("Will use module ~ts to import definitions (if definition file/directory/source has changed)", [Mod]), CurrentHash = rabbit_definitions_hashing:stored_global_hash(), - rabbit_log:debug("Previously stored hash value of imported definitions: ~ts...", [binary:part(rabbit_misc:hexify(CurrentHash), 0, 12)]), + ?LOG_DEBUG("Previously stored hash value of imported definitions: ~ts...", [binary:part(rabbit_misc:hexify(CurrentHash), 0, 12)]), Algo = rabbit_definitions_hashing:hashing_algorithm(), case Mod:load_with_hashing(Proplist, CurrentHash, Algo) of {error, Err} -> {error, Err}; CurrentHash -> - rabbit_log:info("Hash value of imported definitions matches current contents"); + ?LOG_INFO("Hash value of imported definitions matches current contents"); UpdatedHash -> - rabbit_log:debug("Hash value of imported definitions has changed to ~ts...", [binary:part(rabbit_misc:hexify(CurrentHash), 0, 12)]), + ?LOG_DEBUG("Hash value of imported definitions has changed to ~ts...", [binary:part(rabbit_misc:hexify(CurrentHash), 0, 12)]), rabbit_definitions_hashing:store_global_hash(UpdatedHash) end end. @@ -467,7 +468,7 @@ should_skip_if_unchanged() -> OptedIn andalso ReachedTargetClusterSize. log_an_error_about_orphaned_objects() -> - rabbit_log:error("Definitions import: some queues, exchanges or bindings in the definition file " + ?LOG_ERROR("Definitions import: some queues, exchanges or bindings in the definition file " "are missing the virtual host field. Such files are produced when definitions of " "a single virtual host are exported. They cannot be used to import definitions at boot time"). @@ -524,7 +525,7 @@ apply_defs(Map, ActingUser, SuccessFun) when is_function(SuccessFun) -> end, fun() -> - rabbit_log:info("There are fewer than target cluster size (~b) nodes online," + ?LOG_INFO("There are fewer than target cluster size (~b) nodes online," " skipping queue and binding import from definitions", [rabbit_nodes:target_cluster_size_hint()]) end @@ -544,7 +545,7 @@ apply_defs(Map, ActingUser, SuccessFun) when is_function(SuccessFun) -> VHost :: vhost:name()) -> 'ok' | {error, term()}. apply_defs(Map, ActingUser, SuccessFun, VHost) when is_function(SuccessFun); is_binary(VHost) -> - rabbit_log:info("Asked to import definitions for a virtual host. Virtual host: ~tp, acting user: ~tp", + ?LOG_INFO("Asked to import definitions for a virtual host. Virtual host: ~tp, acting user: ~tp", [VHost, ActingUser]), try validate_limits(Map, VHost), @@ -562,7 +563,7 @@ apply_defs(Map, ActingUser, SuccessFun, VHost) when is_function(SuccessFun); is_ end, fun() -> - rabbit_log:info("There are fewer than target cluster size (~b) nodes online," + ?LOG_INFO("There are fewer than target cluster size (~b) nodes online," " skipping queue and binding import from definitions", [rabbit_nodes:target_cluster_size_hint()]) end @@ -589,7 +590,7 @@ sequential_for_all0(Category, ActingUser, Definitions, Fun) -> List -> case length(List) of 0 -> ok; - N -> rabbit_log:info("Importing sequentially ~tp ~ts...", [N, human_readable_category_name(Category)]) + N -> ?LOG_INFO("Importing sequentially ~tp ~ts...", [N, human_readable_category_name(Category)]) end, [begin %% keys are expected to be atoms @@ -626,7 +627,7 @@ concurrent_for_all0(Category, ActingUser, Definitions, Fun) -> List -> case length(List) of 0 -> ok; - N -> rabbit_log:info("Importing concurrently ~tp ~ts...", [N, human_readable_category_name(Category)]) + N -> ?LOG_INFO("Importing concurrently ~tp ~ts...", [N, human_readable_category_name(Category)]) end, WorkPoolFun = fun(M) -> Fun(atomize_keys(M), ActingUser) @@ -664,7 +665,7 @@ do_concurrent_for_all(List, WorkPoolFun) -> WorkPoolFun(M) catch {error, E} -> gatherer:in(Gatherer, {error, E}); _:E:Stacktrace -> - rabbit_log:debug("Definition import: a work pool operation has thrown an exception ~st, stacktrace: ~p", + ?LOG_DEBUG("Definition import: a work pool operation has thrown an exception ~st, stacktrace: ~p", [E, Stacktrace]), gatherer:in(Gatherer, {error, E}) end, @@ -706,7 +707,7 @@ format({no_such_vhost, VHost}) -> format({vhost_limit_exceeded, ErrMsg}) -> rabbit_data_coercion:to_binary(ErrMsg); format({shutdown, _} = Error) -> - rabbit_log:debug("Metadata store is unavailable: ~p", [Error]), + ?LOG_DEBUG("Metadata store is unavailable: ~p", [Error]), rabbit_data_coercion:to_binary( rabbit_misc:format("Metadata store is unavailable. Please try again.", [])); format(E) -> @@ -825,11 +826,11 @@ add_queue(VHost, Queue, ActingUser) -> add_queue_int(_Queue, R = #resource{kind = queue, name = <<"amq.", _/binary>>}, ActingUser) -> Name = R#resource.name, - rabbit_log:warning("Skipping import of a queue whose name begins with 'amq.', " + ?LOG_WARNING("Skipping import of a queue whose name begins with 'amq.', " "name: ~ts, acting user: ~ts", [Name, ActingUser]); add_queue_int(_Queue, R = #resource{kind = queue, virtual_host = undefined}, ActingUser) -> Name = R#resource.name, - rabbit_log:warning("Skipping import of a queue with an unset virtual host field, " + ?LOG_WARNING("Skipping import of a queue with an unset virtual host field, " "name: ~ts, acting user: ~ts", [Name, ActingUser]); add_queue_int(Queue, Name = #resource{virtual_host = VHostName}, ActingUser) -> case rabbit_amqqueue:exists(Name) of @@ -862,11 +863,11 @@ add_exchange(VHost, Exchange, ActingUser) -> add_exchange_int(Exchange, rv(VHost, exchange, Exchange), ActingUser). add_exchange_int(_Exchange, #resource{kind = exchange, name = <<"">>}, ActingUser) -> - rabbit_log:warning("Not importing the default exchange, acting user: ~ts", [ActingUser]); + ?LOG_WARNING("Not importing the default exchange, acting user: ~ts", [ActingUser]); add_exchange_int(_Exchange, R = #resource{kind = exchange, name = <<"amq.", _/binary>>}, ActingUser) -> Name = R#resource.name, - rabbit_log:warning("Skipping import of an exchange whose name begins with 'amq.', " + ?LOG_WARNING("Skipping import of an exchange whose name begins with 'amq.', " "name: ~ts, acting user: ~ts", [Name, ActingUser]); add_exchange_int(Exchange, Name, ActingUser) -> case rabbit_exchange:exists(Name) of @@ -934,7 +935,7 @@ validate_limits(All) -> undefined -> ok; Queues0 -> {ok, VHostMap} = filter_out_existing_queues(Queues0), - _ = rabbit_log:debug("Definition import. Virtual host map for validation: ~p", [VHostMap]), + _ = ?LOG_DEBUG("Definition import. Virtual host map for validation: ~p", [VHostMap]), maps:fold(fun validate_vhost_limit/3, ok, VHostMap) end. diff --git a/deps/rabbit/src/rabbit_definitions_hashing.erl b/deps/rabbit/src/rabbit_definitions_hashing.erl index c239cb1244d2..ba14410e7224 100644 --- a/deps/rabbit/src/rabbit_definitions_hashing.erl +++ b/deps/rabbit/src/rabbit_definitions_hashing.erl @@ -20,6 +20,7 @@ -behaviour(rabbit_runtime_parameter). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -import(rabbit_misc, [pget/2, pget/3]). @@ -109,7 +110,7 @@ stored_vhost_specific_hash(VHostName) -> -spec store_global_hash(Value :: term()) -> ok. store_global_hash(Value) -> - rabbit_log:debug("Storing global imported definitions content hash, hex value: ~ts", [rabbit_misc:hexify(Value)]), + ?LOG_DEBUG("Storing global imported definitions content hash, hex value: ~ts", [rabbit_misc:hexify(Value)]), store_global_hash(Value, ?INTERNAL_USER). -spec store_global_hash(Value0 :: term(), Username :: rabbit_types:username()) -> ok. diff --git a/deps/rabbit/src/rabbit_definitions_import_https.erl b/deps/rabbit/src/rabbit_definitions_import_https.erl index 4ec643c84883..efd316dadf9f 100644 --- a/deps/rabbit/src/rabbit_definitions_import_https.erl +++ b/deps/rabbit/src/rabbit_definitions_import_https.erl @@ -14,6 +14,9 @@ %% * rabbit_definitions_import_local_filesystem %% * rabbit_definitions_hashing -module(rabbit_definitions_import_https). + +-include_lib("kernel/include/logger.hrl"). + -export([ is_enabled/0, load/1, @@ -47,8 +50,8 @@ is_enabled() -> -spec load(Proplist :: list() | map()) -> ok | {error, term()}. load(Proplist) -> URL = pget(url, Proplist), - rabbit_log:info("Applying definitions from a remote URL"), - rabbit_log:debug("HTTPS URL: ~ts", [URL]), + ?LOG_INFO("Applying definitions from a remote URL"), + ?LOG_DEBUG("HTTPS URL: ~ts", [URL]), TLSOptions0 = tls_options_or_default(Proplist), TLSOptions = rabbit_ssl:wrap_password_opt(TLSOptions0), HTTPOptions = http_options(TLSOptions), @@ -57,8 +60,8 @@ load(Proplist) -> -spec load_with_hashing(Proplist :: list() | map(), PreviousHash :: binary() | 'undefined', Algo :: crypto:sha1() | crypto:sha2()) -> binary() | 'undefined'. load_with_hashing(Proplist, PreviousHash, Algo) -> URL = pget(url, Proplist), - rabbit_log:info("Applying definitions from a remote URL"), - rabbit_log:debug("Loading definitions with content hashing enabled, HTTPS URL: ~ts, previous hash value: ~ts", + ?LOG_INFO("Applying definitions from a remote URL"), + ?LOG_DEBUG("Loading definitions with content hashing enabled, HTTPS URL: ~ts, previous hash value: ~ts", [URL, rabbit_misc:hexify(PreviousHash)]), TLSOptions = tls_options_or_default(Proplist), @@ -67,20 +70,20 @@ load_with_hashing(Proplist, PreviousHash, Algo) -> case httpc_get(URL, HTTPOptions) of %% 2XX {ok, {{_, Code, _}, _Headers, Body}} when Code div 100 == 2 -> - rabbit_log:debug("Requested definitions from remote URL '~ts', response code: ~b", [URL, Code]), - rabbit_log:debug("Requested definitions from remote URL '~ts', body: ~tp", [URL, Body]), + ?LOG_DEBUG("Requested definitions from remote URL '~ts', response code: ~b", [URL, Code]), + ?LOG_DEBUG("Requested definitions from remote URL '~ts', body: ~tp", [URL, Body]), case rabbit_definitions_hashing:hash(Algo, Body) of PreviousHash -> PreviousHash; Other -> - rabbit_log:debug("New hash: ~ts", [rabbit_misc:hexify(Other)]), + ?LOG_DEBUG("New hash: ~ts", [rabbit_misc:hexify(Other)]), _ = import_raw(Body), Other end; {ok, {{_, Code, _}, _Headers, _Body}} when Code >= 400 -> - rabbit_log:debug("Requested definitions from remote URL '~ts', response code: ~b", [URL, Code]), + ?LOG_DEBUG("Requested definitions from remote URL '~ts', response code: ~b", [URL, Code]), {error, {could_not_read_defs, {URL, rabbit_misc:format("URL request failed with response code ~b", [Code])}}}; {error, Reason} -> - rabbit_log:error("Requested definitions from remote URL '~ts', error: ~tp", [URL, Reason]), + ?LOG_ERROR("Requested definitions from remote URL '~ts', error: ~tp", [URL, Reason]), {error, {could_not_read_defs, {URL, Reason}}} end. @@ -93,14 +96,14 @@ load_from_url(URL, HTTPOptions0) -> case httpc_get(URL, HTTPOptions0) of %% 2XX {ok, {{_, Code, _}, _Headers, Body}} when Code div 100 == 2 -> - rabbit_log:debug("Requested definitions from remote URL '~ts', response code: ~b", [URL, Code]), - rabbit_log:debug("Requested definitions from remote URL '~ts', body: ~tp", [URL, Body]), + ?LOG_DEBUG("Requested definitions from remote URL '~ts', response code: ~b", [URL, Code]), + ?LOG_DEBUG("Requested definitions from remote URL '~ts', body: ~tp", [URL, Body]), import_raw(Body); {ok, {{_, Code, _}, _Headers, _Body}} when Code >= 400 -> - rabbit_log:debug("Requested definitions from remote URL '~ts', response code: ~b", [URL, Code]), + ?LOG_DEBUG("Requested definitions from remote URL '~ts', response code: ~b", [URL, Code]), {error, {could_not_read_defs, {URL, rabbit_misc:format("URL request failed with response code ~b", [Code])}}}; {error, Reason} -> - rabbit_log:error("Requested definitions from remote URL '~ts', error: ~tp", [URL, Reason]), + ?LOG_ERROR("Requested definitions from remote URL '~ts', error: ~tp", [URL, Reason]), {error, {could_not_read_defs, {URL, Reason}}} end. diff --git a/deps/rabbit/src/rabbit_definitions_import_local_filesystem.erl b/deps/rabbit/src/rabbit_definitions_import_local_filesystem.erl index 0643b347244f..2cabb4f2e354 100644 --- a/deps/rabbit/src/rabbit_definitions_import_local_filesystem.erl +++ b/deps/rabbit/src/rabbit_definitions_import_local_filesystem.erl @@ -15,6 +15,9 @@ %% * rabbit_definitions_import_http %% * rabbit_definitions_hashing -module(rabbit_definitions_import_local_filesystem). + +-include_lib("kernel/include/logger.hrl"). + -export([ is_enabled/0, %% definition source options @@ -48,7 +51,7 @@ load(Proplist) when is_list(Proplist) -> case pget(local_path, Proplist, undefined) of undefined -> {error, "local definition file path is not configured: local_path is not set"}; Path -> - rabbit_log:debug("Asked to import definitions from a local file or directory at '~ts'", [Path]), + ?LOG_DEBUG("Asked to import definitions from a local file or directory at '~ts'", [Path]), IsDir = filelib:is_dir(Path), case IsDir of true -> @@ -75,7 +78,7 @@ load_with_hashing(Proplist, PreviousHash, Algo) -> -spec load_with_hashing(IsDir :: boolean(), Path :: file:name_all(), PreviousHash :: binary() | 'undefined', Algo :: crypto:sha1() | crypto:sha2()) -> binary() | 'undefined'. load_with_hashing(IsDir, Path, PreviousHash, Algo) when is_boolean(IsDir) -> - rabbit_log:debug("Loading definitions with content hashing enabled, path: ~ts, is directory?: ~tp, previous hash value: ~ts", + ?LOG_DEBUG("Loading definitions with content hashing enabled, path: ~ts, is directory?: ~tp, previous hash value: ~ts", [Path, IsDir, rabbit_misc:hexify(PreviousHash)]), case compiled_definitions_from_local_path(IsDir, Path) of %% the directory is empty or no files could be read @@ -87,12 +90,12 @@ load_with_hashing(IsDir, Path, PreviousHash, Algo) when is_boolean(IsDir) -> case rabbit_definitions_hashing:hash(Algo, Defs) of PreviousHash -> PreviousHash; Other -> - rabbit_log:debug("New hash: ~ts", [rabbit_misc:hexify(Other)]), + ?LOG_DEBUG("New hash: ~ts", [rabbit_misc:hexify(Other)]), _ = load_from_local_path(IsDir, Path), Other end; false -> - rabbit_log:error("Definitions file at path ~p failed validation. The file must be a valid JSON document " + ?LOG_ERROR("Definitions file at path ~p failed validation. The file must be a valid JSON document " "and all virtual host-scoped resources must have a virtual host field to be set. " "Definition files exported for a single virtual host CANNOT be imported at boot time", [Path]), {error, not_json} @@ -107,10 +110,10 @@ location() -> -spec load_from_local_path(IsDir :: boolean(), Path :: file:name_all()) -> ok | {error, term()}. load_from_local_path(true, Dir) -> - rabbit_log:info("Applying definitions from directory ~ts", [Dir]), + ?LOG_INFO("Applying definitions from directory ~ts", [Dir]), load_from_files(file:list_dir(Dir), Dir); load_from_local_path(false, File) -> - rabbit_log:info("Applying definitions from regular file at ~ts", [File]), + ?LOG_INFO("Applying definitions from regular file at ~ts", [File]), load_from_single_file(File). %% @@ -169,7 +172,7 @@ compiled_definitions_from_local_path(true = _IsDir, Dir) -> end, ReadResults), [Body || {ok, Body} <- Successes]; {error, E} -> - rabbit_log:error("Could not list files in '~ts', error: ~tp", [Dir, E]), + ?LOG_ERROR("Could not list files in '~ts', error: ~tp", [Dir, E]), {error, {could_not_read_defs, {Dir, E}}} end; compiled_definitions_from_local_path(false = _IsDir, Path) -> @@ -184,7 +187,7 @@ read_file_contents(Path) -> {ok, Body} -> Body; {error, E} -> - rabbit_log:error("Could not read definitions from file at '~ts', error: ~tp", [Path, E]), + ?LOG_ERROR("Could not read definitions from file at '~ts', error: ~tp", [Path, E]), {error, {could_not_read_defs, {Path, E}}} end. @@ -193,7 +196,7 @@ load_from_files({ok, Filenames0}, Dir) -> Filenames2 = [filename:join(Dir, F) || F <- Filenames1], load_from_multiple_files(Filenames2); load_from_files({error, E}, Dir) -> - rabbit_log:error("Could not read definitions from directory ~ts, Error: ~tp", [Dir, E]), + ?LOG_ERROR("Could not read definitions from directory ~ts, Error: ~tp", [Dir, E]), {error, {could_not_read_defs, E}}. load_from_multiple_files([]) -> @@ -205,7 +208,7 @@ load_from_multiple_files([File|Rest]) -> end. load_from_single_file(Path) -> - rabbit_log:debug("Will try to load definitions from a local file or directory at '~ts'", [Path]), + ?LOG_DEBUG("Will try to load definitions from a local file or directory at '~ts'", [Path]), case file:read_file_info(Path, [raw]) of {ok, FileInfo} -> @@ -215,10 +218,10 @@ load_from_single_file(Path) -> true -> case rabbit_misc:raw_read_file(Path) of {ok, Body} -> - rabbit_log:info("Applying definitions from file at '~ts'", [Path]), + ?LOG_INFO("Applying definitions from file at '~ts'", [Path]), import_raw(Body); {error, E} -> - rabbit_log:error("Could not read definitions from file at '~ts', error: ~tp", [Path, E]), + ?LOG_ERROR("Could not read definitions from file at '~ts', error: ~tp", [Path, E]), {error, {could_not_read_defs, {Path, E}}} end; false -> diff --git a/deps/rabbit/src/rabbit_disk_monitor.erl b/deps/rabbit/src/rabbit_disk_monitor.erl index e1658d5de79b..292bce853d79 100644 --- a/deps/rabbit/src/rabbit_disk_monitor.erl +++ b/deps/rabbit/src/rabbit_disk_monitor.erl @@ -7,6 +7,9 @@ -module(rabbit_disk_monitor). +-include_lib("kernel/include/logger.hrl"). + + %% Disk monitoring server. Monitors free disk space %% periodically and sets alarms when it is below a certain %% watermark (configurable either as an absolute value or @@ -145,7 +148,7 @@ init([Limit]) -> {ok, State4}. handle_call({set_disk_free_limit, _}, _From, #state{enabled = false} = State) -> - rabbit_log:info("Cannot set disk free limit: " + ?LOG_INFO("Cannot set disk free limit: " "disabled disk free space monitoring", []), {reply, ok, State}; @@ -163,22 +166,22 @@ handle_call({set_max_check_interval, MaxInterval}, _From, State) -> handle_call({set_enabled, _Enabled = true}, _From, State = #state{enabled = true}) -> _ = start_timer(set_disk_limits(State, State#state.limit)), - rabbit_log:info("Free disk space monitor was already enabled"), + ?LOG_INFO("Free disk space monitor was already enabled"), {reply, ok, State#state{enabled = true}}; handle_call({set_enabled, _Enabled = true}, _From, State = #state{enabled = false}) -> _ = start_timer(set_disk_limits(State, State#state.limit)), - rabbit_log:info("Free disk space monitor was manually enabled"), + ?LOG_INFO("Free disk space monitor was manually enabled"), {reply, ok, State#state{enabled = true}}; handle_call({set_enabled, _Enabled = false}, _From, State = #state{enabled = true}) -> _ = erlang:cancel_timer(State#state.timer), - rabbit_log:info("Free disk space monitor was manually disabled"), + ?LOG_INFO("Free disk space monitor was manually disabled"), {reply, ok, State#state{enabled = false}}; handle_call({set_enabled, _Enabled = false}, _From, State = #state{enabled = false}) -> _ = erlang:cancel_timer(State#state.timer), - rabbit_log:info("Free disk space monitor was already disabled"), + ?LOG_INFO("Free disk space monitor was already disabled"), {reply, ok, State#state{enabled = false}}; handle_call(_Request, _From, State) -> @@ -194,7 +197,7 @@ handle_info(update, State) -> {noreply, start_timer(internal_update(State))}; handle_info(Info, State) -> - rabbit_log:debug("~tp unhandled msg: ~tp", [?MODULE, Info]), + ?LOG_DEBUG("~tp unhandled msg: ~tp", [?MODULE, Info]), {noreply, State}. terminate(_Reason, _State) -> @@ -271,7 +274,7 @@ set_max_check_interval(MaxInterval, State) -> set_disk_limits(State, Limit0) -> Limit = interpret_limit(Limit0), State1 = State#state { limit = Limit }, - rabbit_log:info("Disk free limit set to ~bMB", + ?LOG_INFO("Disk free limit set to ~bMB", [trunc(Limit / 1000000)]), ets:insert(?ETS_NAME, {disk_free_limit, Limit}), internal_update(State1). @@ -309,7 +312,7 @@ get_disk_free(Dir, {win32, _}, not_used) -> % "c:/Users/username/AppData/Roaming/RabbitMQ/db/rabbit2@username-z01-mnesia" case win32_get_drive_letter(Dir) of error -> - rabbit_log:warning("Expected the mnesia directory absolute " + ?LOG_WARNING("Expected the mnesia directory absolute " "path to start with a drive letter like " "'C:'. The path is: '~tp'", [Dir]), {ok, Free} = win32_get_disk_free_dir(Dir), @@ -340,7 +343,7 @@ get_disk_free(Dir, {win32, _}, not_used) -> %% could not compute the result 'NaN'; _:Reason:_ -> - rabbit_log:warning("Free disk space monitoring failed to retrieve the amount of available space: ~p", [Reason]), + ?LOG_WARNING("Free disk space monitoring failed to retrieve the amount of available space: ~p", [Reason]), %% could not compute the result 'NaN' end @@ -405,13 +408,13 @@ interpret_limit(Absolute) -> case rabbit_resource_monitor_misc:parse_information_unit(Absolute) of {ok, ParsedAbsolute} -> ParsedAbsolute; {error, parse_error} -> - rabbit_log:error("Unable to parse disk_free_limit value ~tp", + ?LOG_ERROR("Unable to parse disk_free_limit value ~tp", [Absolute]), ?DEFAULT_DISK_FREE_LIMIT end. emit_update_info(StateStr, CurrentFree, Limit) -> - rabbit_log:info( + ?LOG_INFO( "Free disk space is ~ts. Free bytes: ~b. Limit: ~b", [StateStr, CurrentFree, Limit]). @@ -432,7 +435,7 @@ interval(#state{limit = Limit, trunc(erlang:max(MinInterval, erlang:min(MaxInterval, IdealInterval))). enable(#state{retries = 0} = State) -> - rabbit_log:error("Free disk space monitor failed to start!"), + ?LOG_ERROR("Free disk space monitor failed to start!"), State; enable(#state{dir = Dir, os = OS, port = Port} = State) -> enable_handle_disk_free(catch get_disk_free(Dir, OS, Port), State). @@ -440,7 +443,7 @@ enable(#state{dir = Dir, os = OS, port = Port} = State) -> enable_handle_disk_free(DiskFree, State) when is_integer(DiskFree) -> enable_handle_total_memory(catch vm_memory_monitor:get_total_memory(), DiskFree, State); enable_handle_disk_free(Error, #state{interval = Interval, retries = Retries} = State) -> - rabbit_log:warning("Free disk space monitor encountered an error " + ?LOG_WARNING("Free disk space monitor encountered an error " "(e.g. failed to parse output from OS tools). " "Retries left: ~b Error:~n~tp", [Retries, Error]), @@ -448,11 +451,11 @@ enable_handle_disk_free(Error, #state{interval = Interval, retries = Retries} = State#state{enabled = false}. enable_handle_total_memory(TotalMemory, DiskFree, #state{limit = Limit} = State) when is_integer(TotalMemory) -> - rabbit_log:info("Enabling free disk space monitoring " + ?LOG_INFO("Enabling free disk space monitoring " "(disk free space: ~b, total memory: ~b)", [DiskFree, TotalMemory]), start_timer(set_disk_limits(State, Limit)); enable_handle_total_memory(Error, _DiskFree, #state{interval = Interval, retries = Retries} = State) -> - rabbit_log:warning("Free disk space monitor encountered an error " + ?LOG_WARNING("Free disk space monitor encountered an error " "retrieving total memory. " "Retries left: ~b Error:~n~tp", [Retries, Error]), @@ -472,6 +475,6 @@ run_os_cmd(Cmd) -> CmdResult after 5000 -> exit(CmdPid, kill), - rabbit_log:error("Command timed out: '~ts'", [Cmd]), + ?LOG_ERROR("Command timed out: '~ts'", [Cmd]), {error, timeout} end. diff --git a/deps/rabbit/src/rabbit_epmd_monitor.erl b/deps/rabbit/src/rabbit_epmd_monitor.erl index 7657334a7d60..c437aa0713b8 100644 --- a/deps/rabbit/src/rabbit_epmd_monitor.erl +++ b/deps/rabbit/src/rabbit_epmd_monitor.erl @@ -7,6 +7,9 @@ -module(rabbit_epmd_monitor). +-include_lib("kernel/include/logger.hrl"). + + -behaviour(gen_server). -export([start_link/0]). @@ -84,19 +87,19 @@ check_epmd(State = #state{mod = Mod, {ok, State#state{port = Port1}}. handle_port_please(init, noport, Me, Port) -> - rabbit_log:info("epmd does not know us, re-registering as ~ts", [Me]), + ?LOG_INFO("epmd does not know us, re-registering as ~ts", [Me]), {ok, Port}; handle_port_please(check, noport, Me, Port) -> - rabbit_log:warning("epmd does not know us, re-registering ~ts at port ~b", [Me, Port]), + ?LOG_WARNING("epmd does not know us, re-registering ~ts at port ~b", [Me, Port]), {ok, Port}; handle_port_please(_, closed, _Me, Port) -> - rabbit_log:error("epmd monitor failed to retrieve our port from epmd: closed"), + ?LOG_ERROR("epmd monitor failed to retrieve our port from epmd: closed"), {ok, Port}; handle_port_please(init, {port, NewPort, _Version}, _Me, _Port) -> - rabbit_log:info("epmd monitor knows us, inter-node communication (distribution) port: ~tp", [NewPort]), + ?LOG_INFO("epmd monitor knows us, inter-node communication (distribution) port: ~tp", [NewPort]), {ok, NewPort}; handle_port_please(check, {port, NewPort, _Version}, _Me, _Port) -> {ok, NewPort}; handle_port_please(_, {error, Error}, _Me, Port) -> - rabbit_log:error("epmd monitor failed to retrieve our port from epmd: ~tp", [Error]), + ?LOG_ERROR("epmd monitor failed to retrieve our port from epmd: ~tp", [Error]), {ok, Port}. diff --git a/deps/rabbit/src/rabbit_exchange.erl b/deps/rabbit/src/rabbit_exchange.erl index 8a57123ad67f..274f22869644 100644 --- a/deps/rabbit/src/rabbit_exchange.erl +++ b/deps/rabbit/src/rabbit_exchange.erl @@ -7,6 +7,7 @@ -module(rabbit_exchange). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([recover/1, policy_changed/2, callback/4, declare/7, assert_equivalence/6, assert_args_equivalence/2, check_type/1, exists/1, @@ -135,7 +136,7 @@ declare(XName, Type, Durable, AutoDelete, Internal, Args, Username) -> Err end; _ -> - rabbit_log:warning("ignoring exchange.declare for exchange ~tp, + ?LOG_WARNING("ignoring exchange.declare for exchange ~tp, exchange.delete in progress~n.", [XName]), {ok, X} end. @@ -531,7 +532,7 @@ peek_serial(XName) -> rabbit_db_exchange:peek_serial(XName). invalid_module(T) -> - rabbit_log:warning("Could not find exchange type ~ts.", [T]), + ?LOG_WARNING("Could not find exchange type ~ts.", [T]), put({xtype_to_module, T}, rabbit_exchange_type_invalid), rabbit_exchange_type_invalid. diff --git a/deps/rabbit/src/rabbit_fifo.erl b/deps/rabbit/src/rabbit_fifo.erl index 25d4cc1d1a16..bbc27d57a1b5 100644 --- a/deps/rabbit/src/rabbit_fifo.erl +++ b/deps/rabbit/src/rabbit_fifo.erl @@ -14,6 +14,7 @@ -dialyzer(no_improper_lists). -include("rabbit_fifo.hrl"). +-include_lib("kernel/include/logger.hrl"). -define(STATE, ?MODULE). @@ -676,7 +677,7 @@ apply(Meta, {dlx, _} = Cmd, checkout(Meta, State0, State1, Effects0); apply(_Meta, Cmd, State) -> %% handle unhandled commands gracefully - rabbit_log:debug("rabbit_fifo: unhandled command ~W", [Cmd, 10]), + ?LOG_DEBUG("rabbit_fifo: unhandled command ~W", [Cmd, 10]), {State, ok, []}. convert_v3_to_v4(#{} = _Meta, StateV3) -> @@ -1157,7 +1158,7 @@ handle_aux(_RaState, _, force_checkpoint, bytes_in = BytesIn} = Aux, RaAux) -> Ts = erlang:system_time(millisecond), #?STATE{cfg = #cfg{resource = QR}} = ra_aux:machine_state(RaAux), - rabbit_log:debug("~ts: rabbit_fifo: forcing checkpoint at ~b", + ?LOG_DEBUG("~ts: rabbit_fifo: forcing checkpoint at ~b", [rabbit_misc:rs(QR), ra_aux:last_applied(RaAux)]), {Check, Effects} = do_checkpoints(Ts, Check0, RaAux, BytesIn, true), {no_reply, Aux#?AUX{last_checkpoint = Check}, RaAux, Effects}; @@ -1178,7 +1179,7 @@ eval_gc(RaAux, MacState, Mem > ?GC_MEM_LIMIT_B -> garbage_collect(), {memory, MemAfter} = erlang:process_info(self(), memory), - rabbit_log:debug("~ts: full GC sweep complete. " + ?LOG_DEBUG("~ts: full GC sweep complete. " "Process memory changed from ~.2fMB to ~.2fMB.", [rabbit_misc:rs(QR), Mem/?MB, MemAfter/?MB]), AuxState#?AUX{gc = Gc#aux_gc{last_raft_idx = Idx}}; @@ -1195,7 +1196,7 @@ force_eval_gc(RaAux, true -> garbage_collect(), {memory, MemAfter} = erlang:process_info(self(), memory), - rabbit_log:debug("~ts: full GC sweep complete. " + ?LOG_DEBUG("~ts: full GC sweep complete. " "Process memory changed from ~.2fMB to ~.2fMB.", [rabbit_misc:rs(QR), Mem/?MB, MemAfter/?MB]), AuxState#?AUX{gc = Gc#aux_gc{last_raft_idx = Idx}}; diff --git a/deps/rabbit/src/rabbit_fifo_client.erl b/deps/rabbit/src/rabbit_fifo_client.erl index f00fb1ad6111..f2f50301da5e 100644 --- a/deps/rabbit/src/rabbit_fifo_client.erl +++ b/deps/rabbit/src/rabbit_fifo_client.erl @@ -11,6 +11,9 @@ %% Handles command tracking and other non-functional concerns. -module(rabbit_fifo_client). +-include_lib("kernel/include/logger.hrl"). + + -export([ init/1, init/2, @@ -143,13 +146,13 @@ enqueue(QName, Correlation, Msg, %% to send it {reject_publish, State0}; {error, {shutdown, delete}} -> - rabbit_log:debug("~ts: QQ ~ts tried to register enqueuer during delete shutdown", + ?LOG_DEBUG("~ts: QQ ~ts tried to register enqueuer during delete shutdown", [?MODULE, rabbit_misc:rs(QName)]), {reject_publish, State0}; {timeout, _} -> {reject_publish, State0}; Err -> - rabbit_log:debug("~ts: QQ ~ts error when registering enqueuer ~p", + ?LOG_DEBUG("~ts: QQ ~ts error when registering enqueuer ~p", [?MODULE, rabbit_misc:rs(QName), Err]), exit(Err) end; @@ -628,7 +631,7 @@ handle_ra_event(QName, Leader, {applied, Seqs}, {ok, _, ActualLeader} when ActualLeader =/= OldLeader -> %% there is a new leader - rabbit_log:debug("~ts: Detected QQ leader change (applied) " + ?LOG_DEBUG("~ts: Detected QQ leader change (applied) " "from ~w to ~w, " "resending ~b pending commands", [?MODULE, OldLeader, ActualLeader, @@ -698,7 +701,7 @@ handle_ra_event(QName, Leader, {machine, leader_change}, pending = Pending} = State0) -> %% we need to update leader %% and resend any pending commands - rabbit_log:debug("~ts: ~s Detected QQ leader change from ~w to ~w, " + ?LOG_DEBUG("~ts: ~s Detected QQ leader change from ~w to ~w, " "resending ~b pending commands", [rabbit_misc:rs(QName), ?MODULE, OldLeader, Leader, maps:size(Pending)]), @@ -710,7 +713,7 @@ handle_ra_event(_QName, _From, {rejected, {not_leader, Leader, _Seq}}, handle_ra_event(QName, _From, {rejected, {not_leader, Leader, _Seq}}, #state{leader = OldLeader, pending = Pending} = State0) -> - rabbit_log:debug("~ts: ~s Detected QQ leader change (rejection) from ~w to ~w, " + ?LOG_DEBUG("~ts: ~s Detected QQ leader change (rejection) from ~w to ~w, " "resending ~b pending commands", [rabbit_misc:rs(QName), ?MODULE, OldLeader, Leader, maps:size(Pending)]), @@ -739,7 +742,7 @@ handle_ra_event(QName, Leader, close_cached_segments, {_TRef, Last, Cache} -> case now_ms() > Last + ?CACHE_SEG_TIMEOUT of true -> - rabbit_log:debug("~ts: closing_cached_segments", + ?LOG_DEBUG("~ts: closing_cached_segments", [rabbit_misc:rs(QName)]), %% its been long enough, evict all _ = ra_flru:evict_all(Cache), @@ -982,7 +985,7 @@ add_delivery_count(DelCntIncr, Tag, #state{consumers = CDels0} = State) -> get_missing_deliveries(State, From, To, ConsumerTag) -> %% find local server ConsumerKey = consumer_key(ConsumerTag, State), - rabbit_log:debug("get_missing_deliveries for consumer '~s' from ~b to ~b", + ?LOG_DEBUG("get_missing_deliveries for consumer '~s' from ~b to ~b", [ConsumerTag, From, To]), Cmd = {get_checked_out, ConsumerKey, lists:seq(From, To)}, ServerId = find_local_or_leader(State), diff --git a/deps/rabbit/src/rabbit_fifo_dlx.erl b/deps/rabbit/src/rabbit_fifo_dlx.erl index 6d281d09245c..cb87da2ea0f3 100644 --- a/deps/rabbit/src/rabbit_fifo_dlx.erl +++ b/deps/rabbit/src/rabbit_fifo_dlx.erl @@ -8,6 +8,7 @@ -include("rabbit_fifo_dlx.hrl"). -include("rabbit_fifo.hrl"). +-include_lib("kernel/include/logger.hrl"). -compile({no_auto_import, [apply/3]}). -export([ @@ -123,7 +124,7 @@ apply(_, {dlx, #checkout{consumer = ConsumerPid, OldConsumerPid -> ok; _ -> - rabbit_log:debug("Terminating ~p since ~p becomes active rabbit_fifo_dlx_worker", + ?LOG_DEBUG("Terminating ~p since ~p becomes active rabbit_fifo_dlx_worker", [OldConsumerPid, ConsumerPid]), ensure_worker_terminated(State0) end, @@ -144,7 +145,7 @@ apply(_, {dlx, #checkout{consumer = ConsumerPid, msg_bytes_checkout = BytesCheckout - BytesMoved}, {State, []}; apply(_, Cmd, DLH, State) -> - rabbit_log:debug("Ignoring command ~tp for dead_letter_handler ~tp", [Cmd, DLH]), + ?LOG_DEBUG("Ignoring command ~tp for dead_letter_handler ~tp", [Cmd, DLH]), {State, []}. -spec discard([msg()], rabbit_dead_letter:reason(), dead_letter_handler(), state()) -> @@ -257,7 +258,7 @@ ensure_worker_started(QRef, #?MODULE{consumer = undefined}) -> ensure_worker_started(QRef, #?MODULE{consumer = #dlx_consumer{pid = Pid}}) -> case is_local_and_alive(Pid) of true -> - rabbit_log:debug("rabbit_fifo_dlx_worker ~tp already started for ~ts", + ?LOG_DEBUG("rabbit_fifo_dlx_worker ~tp already started for ~ts", [Pid, rabbit_misc:rs(QRef)]); false -> start_worker(QRef) @@ -269,7 +270,7 @@ ensure_worker_started(QRef, #?MODULE{consumer = #dlx_consumer{pid = Pid}}) -> %% Ra server process crash in which case another Ra node will become leader. start_worker(QRef) -> {ok, Pid} = supervisor:start_child(rabbit_fifo_dlx_sup, [QRef]), - rabbit_log:debug("started rabbit_fifo_dlx_worker ~tp for ~ts", + ?LOG_DEBUG("started rabbit_fifo_dlx_worker ~tp for ~ts", [Pid, rabbit_misc:rs(QRef)]). ensure_worker_terminated(#?MODULE{consumer = undefined}) -> @@ -280,7 +281,7 @@ ensure_worker_terminated(#?MODULE{consumer = #dlx_consumer{pid = Pid}}) -> %% Note that we can't return a mod_call effect here %% because mod_call is executed on the leader only. ok = supervisor:terminate_child(rabbit_fifo_dlx_sup, Pid), - rabbit_log:debug("terminated rabbit_fifo_dlx_worker ~tp", [Pid]); + ?LOG_DEBUG("terminated rabbit_fifo_dlx_worker ~tp", [Pid]); false -> ok end. diff --git a/deps/rabbit/src/rabbit_fifo_dlx_client.erl b/deps/rabbit/src/rabbit_fifo_dlx_client.erl index b1063bef0f6c..3987d6431310 100644 --- a/deps/rabbit/src/rabbit_fifo_dlx_client.erl +++ b/deps/rabbit/src/rabbit_fifo_dlx_client.erl @@ -6,6 +6,9 @@ -module(rabbit_fifo_dlx_client). +-include_lib("kernel/include/logger.hrl"). + + -export([checkout/3, settle/2, handle_ra_event/3, overview/1]). @@ -47,11 +50,11 @@ process_command(Cmd, #state{leader = Leader} = State, Tries) -> {ok, ok, Leader} -> {ok, State#state{leader = Leader}}; {ok, ok, NonLocalLeader} -> - rabbit_log:warning("Failed to process command ~tp on quorum queue leader ~tp because actual leader is ~tp.", + ?LOG_WARNING("Failed to process command ~tp on quorum queue leader ~tp because actual leader is ~tp.", [Cmd, Leader, NonLocalLeader]), {error, non_local_leader}; Err -> - rabbit_log:warning("Failed to process command ~tp on quorum queue leader ~tp: ~tp~n" + ?LOG_WARNING("Failed to process command ~tp on quorum queue leader ~tp: ~tp~n" "Trying ~b more time(s)...", [Cmd, Leader, Err, Tries]), process_command(Cmd, State, Tries - 1) @@ -63,7 +66,7 @@ handle_ra_event(Leader, {dlx_delivery, _} = Del, #state{leader = _Leader} = State) when node(Leader) == node() -> handle_delivery(Del, State); handle_ra_event(From, Evt, State) -> - rabbit_log:debug("Ignoring ra event ~tp from ~tp", [Evt, From]), + ?LOG_DEBUG("Ignoring ra event ~tp from ~tp", [Evt, From]), {ok, State, []}. handle_delivery({dlx_delivery, [{FstId, _} | _] = IdMsgs}, diff --git a/deps/rabbit/src/rabbit_fifo_dlx_worker.erl b/deps/rabbit/src/rabbit_fifo_dlx_worker.erl index 6dc08d9f66bc..4084793846ab 100644 --- a/deps/rabbit/src/rabbit_fifo_dlx_worker.erl +++ b/deps/rabbit/src/rabbit_fifo_dlx_worker.erl @@ -25,6 +25,7 @@ -include("mc.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). % -include_lib("rabbit_common/include/rabbit_framing.hrl"). -behaviour(gen_server). @@ -135,7 +136,7 @@ terminate(_Reason, State) -> cancel_timer(State). handle_call(Request, From, State) -> - rabbit_log:info("~ts received unhandled call from ~tp: ~tp", [?MODULE, From, Request]), + ?LOG_INFO("~ts received unhandled call from ~tp: ~tp", [?MODULE, From, Request]), {noreply, State}. handle_cast({dlx_event, _LeaderPid, lookup_topology}, @@ -169,7 +170,7 @@ handle_cast(settle_timeout, State0) -> State = State0#state{timer = undefined}, redeliver_and_ack(State); handle_cast(Request, State) -> - rabbit_log:info("~ts received unhandled cast ~tp", [?MODULE, Request]), + ?LOG_INFO("~ts received unhandled cast ~tp", [?MODULE, Request]), {noreply, State}. redeliver_and_ack(State0) -> @@ -183,7 +184,7 @@ handle_info({'DOWN', Ref, process, _, _}, queue_ref = QRef}) -> %% Source quorum queue is down. Therefore, terminate ourself. %% The new leader will re-create another dlx_worker. - rabbit_log:debug("~ts terminating itself because leader of ~ts is down...", + ?LOG_DEBUG("~ts terminating itself because leader of ~ts is down...", [?MODULE, rabbit_misc:rs(QRef)]), supervisor:terminate_child(rabbit_fifo_dlx_sup, self()); handle_info({{'DOWN', QName}, _MRef, process, QPid, Reason}, @@ -197,7 +198,7 @@ handle_info({{'DOWN', QName}, _MRef, process, QPid, Reason}, remove_queue(QRef, State0#state{queue_type_state = QTypeState}) end; handle_info(Info, State) -> - rabbit_log:info("~ts received unhandled info ~tp", [?MODULE, Info]), + ?LOG_INFO("~ts received unhandled info ~tp", [?MODULE, Info]), {noreply, State}. code_change(_OldVsn, State, _Extra) -> @@ -219,7 +220,7 @@ remove_queue(QRef, #state{pendings = Pendings0, queue_type_state = QTypeState}}. wait_for_queue_deleted(QRef, 0) -> - rabbit_log:debug("Received deletion event for ~ts but queue still exists in ETS table.", + ?LOG_DEBUG("Received deletion event for ~ts but queue still exists in ETS table.", [rabbit_misc:rs(QRef)]); wait_for_queue_deleted(QRef, N) -> case rabbit_amqqueue:exists(QRef) of @@ -289,7 +290,7 @@ rejected(SeqNo, Qs, Pendings) end, Pendings); false -> - rabbit_log:debug("Ignoring rejection for unknown sequence number ~b " + ?LOG_DEBUG("Ignoring rejection for unknown sequence number ~b " "from target dead letter queues ~tp", [SeqNo, Qs]), Pendings @@ -386,7 +387,7 @@ deliver_to_queues(Msg, Options, Qs, #state{queue_type_state = QTypeState0, %% we won't rely on rabbit_fifo_client to re-deliver on behalf of us %% (and therefore preventing messages to get stuck in our 'unsettled' state). QNames = queue_names(Qs), - rabbit_log:debug("Failed to deliver message with seq_no ~b to " + ?LOG_DEBUG("Failed to deliver message with seq_no ~b to " "queues ~tp: ~tp", [SeqNo, QNames, Reason]), {State0#state{pendings = rejected(SeqNo, QNames, Pendings)}, []} @@ -419,7 +420,7 @@ handle_settled0(QRef, MsgSeq, #state{pendings = Pendings, settled = [QRef | Settled]}, State#state{pendings = maps:update(MsgSeq, Pend, Pendings)}; error -> - rabbit_log:debug("Ignoring publisher confirm for unknown sequence number ~b " + ?LOG_DEBUG("Ignoring publisher confirm for unknown sequence number ~b " "from target dead letter ~ts", [MsgSeq, rabbit_misc:rs(QRef)]), State @@ -625,7 +626,7 @@ log_missing_dlx_once(#state{exchange_ref = SameDlx, log_missing_dlx_once(#state{exchange_ref = DlxResource, queue_ref = QueueResource, logged = Logged} = State) -> - rabbit_log:warning("Cannot forward any dead-letter messages from source quorum ~ts because " + ?LOG_WARNING("Cannot forward any dead-letter messages from source quorum ~ts because " "its configured dead-letter-exchange ~ts does not exist. " "Either create the configured dead-letter-exchange or re-configure " "the dead-letter-exchange policy for the source quorum queue to prevent " @@ -642,7 +643,7 @@ log_no_route_once(#state{queue_ref = QueueResource, exchange_ref = DlxResource, routing_key = RoutingKey, logged = Logged} = State) -> - rabbit_log:warning("Cannot forward any dead-letter messages from source quorum ~ts " + ?LOG_WARNING("Cannot forward any dead-letter messages from source quorum ~ts " "with configured dead-letter-exchange ~ts and configured " "dead-letter-routing-key '~ts'. This can happen either if the dead-letter " "routing topology is misconfigured (for example no queue bound to " @@ -663,7 +664,7 @@ log_cycle_once(Queues, _, #state{logged = Logged} = State) log_cycle_once(Queues, RoutingKeys, #state{exchange_ref = DlxResource, queue_ref = QueueResource, logged = Logged} = State) -> - rabbit_log:warning("Dead-letter queues cycle detected for source quorum ~ts " + ?LOG_WARNING("Dead-letter queues cycle detected for source quorum ~ts " "with dead-letter exchange ~ts and routing keys ~tp: ~tp " "This message will not be logged again.", [rabbit_misc:rs(QueueResource), rabbit_misc:rs(DlxResource), diff --git a/deps/rabbit/src/rabbit_fifo_v0.erl b/deps/rabbit/src/rabbit_fifo_v0.erl index 20b37494bb23..7e70d741f2c4 100644 --- a/deps/rabbit/src/rabbit_fifo_v0.erl +++ b/deps/rabbit/src/rabbit_fifo_v0.erl @@ -15,6 +15,7 @@ -include("rabbit_fifo_v0.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([ init/1, @@ -673,7 +674,7 @@ eval_gc(Log, #?STATE{cfg = #cfg{resource = QR}} = MacState, Mem > ?GC_MEM_LIMIT_B -> garbage_collect(), {memory, MemAfter} = erlang:process_info(self(), memory), - rabbit_log:debug("~ts: full GC sweep complete. " + ?LOG_DEBUG("~ts: full GC sweep complete. " "Process memory changed from ~.2fMB to ~.2fMB.", [rabbit_misc:rs(QR), Mem/?MB, MemAfter/?MB]), AuxState#aux{gc = Gc#aux_gc{last_raft_idx = Idx}}; diff --git a/deps/rabbit/src/rabbit_fifo_v1.erl b/deps/rabbit/src/rabbit_fifo_v1.erl index 1e438405afe8..0d3fe23cf259 100644 --- a/deps/rabbit/src/rabbit_fifo_v1.erl +++ b/deps/rabbit/src/rabbit_fifo_v1.erl @@ -15,6 +15,7 @@ -include("rabbit_fifo_v1.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([ init/1, @@ -533,7 +534,7 @@ apply(_Meta, {machine_version, 0, 1}, V0State) -> {State, ok, []}; apply(_Meta, Cmd, State) -> %% handle unhandled commands gracefully - rabbit_log:debug("rabbit_fifo: unhandled command ~W", [Cmd, 10]), + ?LOG_DEBUG("rabbit_fifo: unhandled command ~W", [Cmd, 10]), {State, ok, []}. convert_v0_to_v1(V0State0) -> @@ -855,7 +856,7 @@ eval_gc(Log, #?STATE{cfg = #cfg{resource = QR}} = MacState, Mem > ?GC_MEM_LIMIT_B -> garbage_collect(), {memory, MemAfter} = erlang:process_info(self(), memory), - rabbit_log:debug("~ts: full GC sweep complete. " + ?LOG_DEBUG("~ts: full GC sweep complete. " "Process memory changed from ~.2fMB to ~.2fMB.", [rabbit_misc:rs(QR), Mem/?MB, MemAfter/?MB]), AuxState#aux{gc = Gc#aux_gc{last_raft_idx = Idx}}; @@ -871,7 +872,7 @@ force_eval_gc(Log, #?STATE{cfg = #cfg{resource = QR}}, true -> garbage_collect(), {memory, MemAfter} = erlang:process_info(self(), memory), - rabbit_log:debug("~ts: full GC sweep complete. " + ?LOG_DEBUG("~ts: full GC sweep complete. " "Process memory changed from ~.2fMB to ~.2fMB.", [rabbit_misc:rs(QR), Mem/?MB, MemAfter/?MB]), AuxState#aux{gc = Gc#aux_gc{last_raft_idx = Idx}}; diff --git a/deps/rabbit/src/rabbit_fifo_v3.erl b/deps/rabbit/src/rabbit_fifo_v3.erl index ad85fe2f3917..73cac6bf7668 100644 --- a/deps/rabbit/src/rabbit_fifo_v3.erl +++ b/deps/rabbit/src/rabbit_fifo_v3.erl @@ -15,6 +15,7 @@ -include("rabbit_fifo_v3.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -define(STATE, rabbit_fifo). @@ -619,7 +620,7 @@ apply(#{index := IncomingRaftIdx} = Meta, {dlx, _} = Cmd, update_smallest_raft_index(IncomingRaftIdx, State, Effects); apply(_Meta, Cmd, State) -> %% handle unhandled commands gracefully - rabbit_log:debug("rabbit_fifo: unhandled command ~W", [Cmd, 10]), + ?LOG_DEBUG("rabbit_fifo: unhandled command ~W", [Cmd, 10]), {State, ok, []}. convert_msg({RaftIdx, {Header, empty}}) when is_integer(RaftIdx) -> @@ -1172,7 +1173,7 @@ eval_gc(Log, #?STATE{cfg = #cfg{resource = QR}} = MacState, Mem > ?GC_MEM_LIMIT_B -> garbage_collect(), {memory, MemAfter} = erlang:process_info(self(), memory), - rabbit_log:debug("~ts: full GC sweep complete. " + ?LOG_DEBUG("~ts: full GC sweep complete. " "Process memory changed from ~.2fMB to ~.2fMB.", [rabbit_misc:rs(QR), Mem/?MB, MemAfter/?MB]), AuxState#?AUX{gc = Gc#aux_gc{last_raft_idx = Idx}}; @@ -1188,7 +1189,7 @@ force_eval_gc(Log, #?STATE{cfg = #cfg{resource = QR}}, true -> garbage_collect(), {memory, MemAfter} = erlang:process_info(self(), memory), - rabbit_log:debug("~ts: full GC sweep complete. " + ?LOG_DEBUG("~ts: full GC sweep complete. " "Process memory changed from ~.2fMB to ~.2fMB.", [rabbit_misc:rs(QR), Mem/?MB, MemAfter/?MB]), AuxState#?AUX{gc = Gc#aux_gc{last_raft_idx = Idx}}; diff --git a/deps/rabbit/src/rabbit_health_check.erl b/deps/rabbit/src/rabbit_health_check.erl index cb4fffd5866a..71ad6ca17ab2 100644 --- a/deps/rabbit/src/rabbit_health_check.erl +++ b/deps/rabbit/src/rabbit_health_check.erl @@ -6,6 +6,9 @@ %% -module(rabbit_health_check). +-include_lib("kernel/include/logger.hrl"). + + %% External API -export([node/1, node/2]). @@ -28,7 +31,7 @@ node(Node, Timeout) -> -spec local() -> ok | {error_string, string()}. local() -> - rabbit_log:warning("rabbitmqctl node_health_check and its HTTP API counterpart are DEPRECATED. " + ?LOG_WARNING("rabbitmqctl node_health_check and its HTTP API counterpart are DEPRECATED. " "See https://www.rabbitmq.com/docs/monitoring#health-checks for replacement options."), run_checks([list_channels, list_queues, alarms, rabbit_node_monitor]). diff --git a/deps/rabbit/src/rabbit_maintenance.erl b/deps/rabbit/src/rabbit_maintenance.erl index 873bc8453d85..172b115530c6 100644 --- a/deps/rabbit/src/rabbit_maintenance.erl +++ b/deps/rabbit/src/rabbit_maintenance.erl @@ -8,6 +8,7 @@ -module(rabbit_maintenance). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). %% FIXME: Ra consistent queries are currently fragile in the sense that the %% query function may run on a remote node and the function reference or MFA @@ -62,13 +63,13 @@ is_enabled() -> -spec drain() -> ok. drain() -> - rabbit_log:warning("This node is being put into maintenance (drain) mode"), + ?LOG_WARNING("This node is being put into maintenance (drain) mode"), mark_as_being_drained(), - rabbit_log:info("Marked this node as undergoing maintenance"), + ?LOG_INFO("Marked this node as undergoing maintenance"), _ = suspend_all_client_listeners(), - rabbit_log:warning("Suspended all listeners and will no longer accept client connections"), + ?LOG_WARNING("Suspended all listeners and will no longer accept client connections"), {ok, NConnections} = close_all_client_connections(), - rabbit_log:warning("Closed ~b local client connections", [NConnections]), + ?LOG_WARNING("Closed ~b local client connections", [NConnections]), %% allow plugins to react e.g. by closing their protocol connections rabbit_event:notify(maintenance_connections_closed, #{ reason => <<"node is being put into maintenance">> @@ -85,19 +86,19 @@ drain() -> rabbit_event:notify(maintenance_draining, #{ reason => <<"node is being put into maintenance">> }), - rabbit_log:info("Node is ready to be shut down for maintenance or upgrade"), + ?LOG_INFO("Node is ready to be shut down for maintenance or upgrade"), ok. -spec revive() -> ok. revive() -> - rabbit_log:info("This node is being revived from maintenance (drain) mode"), + ?LOG_INFO("This node is being revived from maintenance (drain) mode"), rabbit_queue_type:revive(), - rabbit_log:info("Resumed all listeners and will accept client connections again"), + ?LOG_INFO("Resumed all listeners and will accept client connections again"), _ = resume_all_client_listeners(), - rabbit_log:info("Resumed all listeners and will accept client connections again"), + ?LOG_INFO("Resumed all listeners and will accept client connections again"), unmark_as_being_drained(), - rabbit_log:info("Marked this node as back from maintenance and ready to serve clients"), + ?LOG_INFO("Marked this node as back from maintenance and ready to serve clients"), %% allow plugins to react rabbit_event:notify(maintenance_revived, #{}), @@ -106,12 +107,12 @@ revive() -> -spec mark_as_being_drained() -> boolean(). mark_as_being_drained() -> - rabbit_log:debug("Marking the node as undergoing maintenance"), + ?LOG_DEBUG("Marking the node as undergoing maintenance"), rabbit_db_maintenance:set(?DRAINING_STATUS). -spec unmark_as_being_drained() -> boolean(). unmark_as_being_drained() -> - rabbit_log:debug("Unmarking the node as undergoing maintenance"), + ?LOG_DEBUG("Unmarking the node as undergoing maintenance"), rabbit_db_maintenance:set(?DEFAULT_STATUS). -spec is_being_drained_local_read(node()) -> boolean(). @@ -157,7 +158,7 @@ filter_out_drained_nodes_consistent_read(Nodes) -> %% but previously established connections won't be interrupted. suspend_all_client_listeners() -> Listeners = rabbit_networking:node_client_listeners(node()), - rabbit_log:info("Asked to suspend ~b client connection listeners. " + ?LOG_INFO("Asked to suspend ~b client connection listeners. " "No new client connections will be accepted until these listeners are resumed!", [length(Listeners)]), Results = lists:foldl(local_listener_fold_fun(fun ranch:suspend_listener/1), [], Listeners), lists:foldl(fun ok_or_first_error/2, ok, Results). @@ -168,7 +169,7 @@ suspend_all_client_listeners() -> %% A resumed listener will accept new client connections. resume_all_client_listeners() -> Listeners = rabbit_networking:node_client_listeners(node()), - rabbit_log:info("Asked to resume ~b client connection listeners. " + ?LOG_INFO("Asked to resume ~b client connection listeners. " "New client connections will be accepted from now on", [length(Listeners)]), Results = lists:foldl(local_listener_fold_fun(fun ranch:resume_listener/1), [], Listeners), lists:foldl(fun ok_or_first_error/2, ok, Results). @@ -180,15 +181,15 @@ close_all_client_connections() -> {ok, length(Pids)}. transfer_leadership_of_metadata_store(TransferCandidates) -> - rabbit_log:info("Will transfer leadership of metadata store with current leader on this node", + ?LOG_INFO("Will transfer leadership of metadata store with current leader on this node", []), case rabbit_khepri:transfer_leadership(TransferCandidates) of {ok, Node} when Node == node(); Node == undefined -> - rabbit_log:info("Skipping leadership transfer of metadata store: current leader is not on this node"); + ?LOG_INFO("Skipping leadership transfer of metadata store: current leader is not on this node"); {ok, Node} -> - rabbit_log:info("Leadership transfer for metadata store on this node has been done. The new leader is ~p", [Node]); + ?LOG_INFO("Leadership transfer for metadata store on this node has been done. The new leader is ~p", [Node]); Error -> - rabbit_log:warning("Skipping leadership transfer of metadata store: ~p", [Error]) + ?LOG_WARNING("Skipping leadership transfer of metadata store: ~p", [Error]) end. -spec primary_replica_transfer_candidate_nodes() -> [node()]. diff --git a/deps/rabbit/src/rabbit_mnesia.erl b/deps/rabbit/src/rabbit_mnesia.erl index 89ef6e726b91..1299293b5b23 100644 --- a/deps/rabbit/src/rabbit_mnesia.erl +++ b/deps/rabbit/src/rabbit_mnesia.erl @@ -8,6 +8,7 @@ -module(rabbit_mnesia). -include_lib("rabbit_common/include/logging.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([%% Main interface init/0, @@ -123,7 +124,7 @@ init() -> NodeType = node_type(), case is_node_type_permitted(NodeType) of false -> - rabbit_log:info( + ?LOG_INFO( "RAM nodes are deprecated and not permitted. This " "node will be converted to a disc node."), init_db_and_upgrade(cluster_nodes(all), disc, @@ -175,7 +176,7 @@ can_join_cluster(DiscoveryNode) -> %% do we think so ourselves? case are_we_clustered_with(DiscoveryNode) of true -> - rabbit_log:info("Asked to join a cluster but already a member of it: ~tp", [ClusterNodes]), + ?LOG_INFO("Asked to join a cluster but already a member of it: ~tp", [ClusterNodes]), {ok, already_member}; false -> Msg = format_inconsistent_cluster_message(DiscoveryNode, node()), @@ -195,7 +196,7 @@ join_cluster(ClusterNodes, NodeType) when is_list(ClusterNodes) -> false -> disc; true -> NodeType end, - rabbit_log:info("Clustering with ~tp as ~tp node", + ?LOG_INFO("Clustering with ~tp as ~tp node", [ClusterNodes, NodeType1]), ok = init_db_with_mnesia(ClusterNodes, NodeType1, true, true, _Retry = true), @@ -230,7 +231,7 @@ reset() -> force_reset() -> ensure_mnesia_not_running(), - rabbit_log:info("Resetting Rabbit forcefully", []), + ?LOG_INFO("Resetting Rabbit forcefully", []), wipe(). reset_gracefully() -> @@ -300,7 +301,7 @@ forget_cluster_node(Node, RemoveWhenOffline) -> {true, false} -> remove_node_offline_node(Node); {true, true} -> e(online_node_offline_flag); {false, false} -> e(offline_node_no_offline_flag); - {false, true} -> rabbit_log:info( + {false, true} -> ?LOG_INFO( "Removing node ~tp from cluster", [Node]), case remove_node_if_mnesia_running(Node) of ok -> ok; @@ -550,7 +551,7 @@ init_db(ClusterNodes, NodeType, CheckOtherNodes) -> ensure_node_type_is_permitted(NodeType), NodeIsVirgin = is_virgin_node(), - rabbit_log:debug("Does data directory looks like that of a blank (uninitialised) node? ~tp", [NodeIsVirgin]), + ?LOG_DEBUG("Does data directory looks like that of a blank (uninitialised) node? ~tp", [NodeIsVirgin]), Nodes = change_extra_db_nodes(ClusterNodes, CheckOtherNodes), %% Note that we use `system_info' here and not the cluster status %% since when we start rabbit for the first time the cluster @@ -744,7 +745,7 @@ remote_node_info(Node) -> on_node_up(Node) -> case running_disc_nodes() of - [Node] -> rabbit_log:info("cluster contains disc nodes again~n"); + [Node] -> ?LOG_INFO("cluster contains disc nodes again~n"); _ -> ok end. @@ -752,7 +753,7 @@ on_node_up(Node) -> on_node_down(_Node) -> case running_disc_nodes() of - [] -> rabbit_log:info("only running disc node went down~n"); + [] -> ?LOG_INFO("only running disc node went down~n"); _ -> ok end. @@ -891,17 +892,17 @@ create_schema() -> false = rabbit_khepri:is_enabled(), stop_mnesia(), - rabbit_log:debug("Will bootstrap a schema database..."), + ?LOG_DEBUG("Will bootstrap a schema database..."), rabbit_misc:ensure_ok(mnesia:create_schema([node()]), cannot_create_schema), - rabbit_log:debug("Bootstraped a schema database successfully"), + ?LOG_DEBUG("Bootstraped a schema database successfully"), start_mnesia(), - rabbit_log:debug("Will create schema database tables"), + ?LOG_DEBUG("Will create schema database tables"), ok = rabbit_table:create(), - rabbit_log:debug("Created schema database tables successfully"), - rabbit_log:debug("Will check schema database integrity..."), + ?LOG_DEBUG("Created schema database tables successfully"), + ?LOG_DEBUG("Will check schema database integrity..."), ensure_schema_integrity(), - rabbit_log:debug("Schema database schema integrity check passed"), + ?LOG_DEBUG("Schema database schema integrity check passed"), ok. remove_node_if_mnesia_running(Node) -> @@ -945,7 +946,7 @@ leave_cluster(Node) -> end. wait_for(Condition) -> - rabbit_log:info("Waiting for ~tp...", [Condition]), + ?LOG_INFO("Waiting for ~tp...", [Condition]), timer:sleep(1000). start_mnesia(CheckConsistency) -> @@ -1067,10 +1068,10 @@ mnesia_and_msg_store_files() -> rabbit_feature_flags:enabled_feature_flags_list_file(), rabbit_khepri:dir()], IgnoredFiles = [filename:basename(File) || File <- IgnoredFiles0], - rabbit_log:debug("Files and directories found in node's data directory: ~ts, of them to be ignored: ~ts", + ?LOG_DEBUG("Files and directories found in node's data directory: ~ts, of them to be ignored: ~ts", [string:join(lists:usort(List0), ", "), string:join(lists:usort(IgnoredFiles), ", ")]), List = List0 -- IgnoredFiles, - rabbit_log:debug("Files and directories found in node's data directory sans ignored ones: ~ts", [string:join(lists:usort(List), ", ")]), + ?LOG_DEBUG("Files and directories found in node's data directory sans ignored ones: ~ts", [string:join(lists:usort(List), ", ")]), List end. diff --git a/deps/rabbit/src/rabbit_msg_store.erl b/deps/rabbit/src/rabbit_msg_store.erl index 5965589bfd11..7ffa783fb402 100644 --- a/deps/rabbit/src/rabbit_msg_store.erl +++ b/deps/rabbit/src/rabbit_msg_store.erl @@ -25,6 +25,7 @@ %%---------------------------------------------------------------------------- -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -type(msg() :: any()). @@ -792,11 +793,11 @@ init([VHost, Type, BaseDir, ClientRefs, StartupFunState]) -> true -> "clean"; false -> "unclean" end, - rabbit_log:debug("Rebuilding message location index after ~ts shutdown...", + ?LOG_DEBUG("Rebuilding message location index after ~ts shutdown...", [Cleanliness]), {CurOffset, State1 = #msstate { current_file = CurFile }} = build_index(CleanShutdown, StartupFunState, State), - rabbit_log:debug("Finished rebuilding index", []), + ?LOG_DEBUG("Finished rebuilding index", []), %% Open the most recent file. {ok, CurHdl} = writer_recover(Dir, CurFile, CurOffset), {ok, State1 #msstate { current_file_handle = CurHdl, @@ -971,7 +972,7 @@ terminate(Reason, State = #msstate { index_ets = IndexEts, {shutdown, _} -> {"", []}; _ -> {" with reason ~0p", [Reason]} end, - rabbit_log:info("Stopping message store for directory '~ts'" ++ ExtraLog, [Dir|ExtraLogArgs]), + ?LOG_INFO("Stopping message store for directory '~ts'" ++ ExtraLog, [Dir|ExtraLogArgs]), %% stop the gc first, otherwise it could be working and we pull %% out the ets tables from under it. ok = rabbit_msg_store_gc:stop(GCPid), @@ -984,7 +985,7 @@ terminate(Reason, State = #msstate { index_ets = IndexEts, case store_file_summary(FileSummaryEts, Dir) of ok -> ok; {error, FSErr} -> - rabbit_log:error("Unable to store file summary" + ?LOG_ERROR("Unable to store file summary" " for vhost message store for directory ~tp~n" "Error: ~tp", [Dir, FSErr]) @@ -994,10 +995,10 @@ terminate(Reason, State = #msstate { index_ets = IndexEts, index_terminate(IndexEts, Dir), case store_recovery_terms([{client_refs, maps:keys(Clients)}], Dir) of ok -> - rabbit_log:info("Message store for directory '~ts' is stopped", [Dir]), + ?LOG_INFO("Message store for directory '~ts' is stopped", [Dir]), ok; {error, RTErr} -> - rabbit_log:error("Unable to save message store recovery terms" + ?LOG_ERROR("Unable to save message store recovery terms" " for directory ~tp~nError: ~tp", [Dir, RTErr]) end, @@ -1703,7 +1704,7 @@ index_terminate(IndexEts, Dir) -> [{extended_info, [object_count]}]) of ok -> ok; {error, Err} -> - rabbit_log:error("Unable to save message store index" + ?LOG_ERROR("Unable to save message store index" " for directory ~tp.~nError: ~tp", [Dir, Err]) end, @@ -1716,11 +1717,11 @@ index_terminate(IndexEts, Dir) -> recover_index_and_client_refs(_Recover, undefined, Dir, _Name) -> {false, index_new(Dir), []}; recover_index_and_client_refs(false, _ClientRefs, Dir, Name) -> - rabbit_log:warning("Message store ~tp: rebuilding indices from scratch", [Name]), + ?LOG_WARNING("Message store ~tp: rebuilding indices from scratch", [Name]), {false, index_new(Dir), []}; recover_index_and_client_refs(true, ClientRefs, Dir, Name) -> Fresh = fun (ErrorMsg, ErrorArgs) -> - rabbit_log:warning("Message store ~tp : " ++ ErrorMsg ++ "~n" + ?LOG_WARNING("Message store ~tp : " ++ ErrorMsg ++ "~n" "rebuilding indices from scratch", [Name | ErrorArgs]), {false, index_new(Dir), []} @@ -1813,9 +1814,9 @@ build_index(true, _StartupFunState, {FileSize, State#msstate{ current_file = File }}; build_index(false, {MsgRefDeltaGen, MsgRefDeltaGenInit}, State = #msstate { dir = Dir }) -> - rabbit_log:debug("Rebuilding message refcount...", []), + ?LOG_DEBUG("Rebuilding message refcount...", []), ok = count_msg_refs(MsgRefDeltaGen, MsgRefDeltaGenInit, State), - rabbit_log:debug("Done rebuilding message refcount", []), + ?LOG_DEBUG("Done rebuilding message refcount", []), {ok, Pid} = gatherer:start_link(), case [filename_to_num(FileName) || FileName <- list_sorted_filenames(Dir, ?FILE_EXTENSION)] of @@ -1829,7 +1830,7 @@ build_index(false, {MsgRefDeltaGen, MsgRefDeltaGenInit}, build_index_worker(Gatherer, #msstate { index_ets = IndexEts, dir = Dir }, File, Files) -> Path = form_filename(Dir, filenum_to_name(File)), - rabbit_log:debug("Rebuilding message location index from ~ts (~B file(s) remaining)", + ?LOG_DEBUG("Rebuilding message location index from ~ts (~B file(s) remaining)", [Path, length(Files)]), %% The scan function already dealt with duplicate messages %% within the file, and only returns valid messages (we do @@ -2001,7 +2002,7 @@ delete_file_if_empty(File, State = #msstate { compact_file(File, State = #gc_state { file_summary_ets = FileSummaryEts }) -> case ets:lookup(FileSummaryEts, File) of [] -> - rabbit_log:debug("File ~tp has already been deleted; no need to compact", + ?LOG_DEBUG("File ~tp has already been deleted; no need to compact", [File]), ok; [#file_summary{file_size = FileSize}] -> @@ -2046,7 +2047,7 @@ compact_file(File, FileSize, %% after truncation. This is a debug message so it doesn't hurt to %% put out more details around what's happening. Reclaimed = FileSize - TruncateSize, - rabbit_log:debug("Compacted segment file number ~tp; ~tp bytes can now be reclaimed", + ?LOG_DEBUG("Compacted segment file number ~tp; ~tp bytes can now be reclaimed", [File, Reclaimed]), %% Tell the message store to update its state. gen_server2:cast(Server, {compacted_file, File}), @@ -2147,7 +2148,7 @@ truncate_file(File, Size, ThresholdTimestamp, #gc_state{ file_summary_ets = File case ets:select(FileHandlesEts, [{{{'_', File}, '$1'}, [{'=<', '$1', ThresholdTimestamp}], ['$$']}], 1) of {[_|_], _Cont} -> - rabbit_log:debug("Asked to truncate file ~p but it has active readers. Deferring.", + ?LOG_DEBUG("Asked to truncate file ~p but it has active readers. Deferring.", [File]), defer; _ -> @@ -2158,7 +2159,7 @@ truncate_file(File, Size, ThresholdTimestamp, #gc_state{ file_summary_ets = File ok = file:close(Fd), true = ets:update_element(FileSummaryEts, File, {#file_summary.file_size, Size}), - rabbit_log:debug("Truncated file number ~tp; new size ~tp bytes", [File, Size]), + ?LOG_DEBUG("Truncated file number ~tp; new size ~tp bytes", [File, Size]), ok end end. @@ -2170,7 +2171,7 @@ delete_file(File, #gc_state { file_summary_ets = FileSummaryEts, dir = Dir }) -> case ets:match_object(FileHandlesEts, {{'_', File}, '_'}, 1) of {[_|_], _Cont} -> - rabbit_log:debug("Asked to delete file ~p but it has active readers. Deferring.", + ?LOG_DEBUG("Asked to delete file ~p but it has active readers. Deferring.", [File]), defer; _ -> @@ -2178,7 +2179,7 @@ delete_file(File, #gc_state { file_summary_ets = FileSummaryEts, file_size = FileSize }] = ets:lookup(FileSummaryEts, File), ok = file:delete(form_filename(Dir, filenum_to_name(File))), true = ets:delete(FileSummaryEts, File), - rabbit_log:debug("Deleted empty file number ~tp; reclaimed ~tp bytes", [File, FileSize]), + ?LOG_DEBUG("Deleted empty file number ~tp; reclaimed ~tp bytes", [File, FileSize]), ok end. diff --git a/deps/rabbit/src/rabbit_networking.erl b/deps/rabbit/src/rabbit_networking.erl index 361b1c1dfaa2..83f06aeec9ac 100644 --- a/deps/rabbit/src/rabbit_networking.erl +++ b/deps/rabbit/src/rabbit_networking.erl @@ -55,6 +55,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include_lib("rabbit_common/include/rabbit_misc.hrl"). +-include_lib("kernel/include/logger.hrl"). %% IANA-suggested ephemeral port range is 49152 to 65535 -define(FIRST_TEST_BIND_PORT, 49152). @@ -90,7 +91,7 @@ boot() -> ok = record_distribution_listener(), _ = application:start(ranch), - rabbit_log:debug("Started Ranch"), + ?LOG_DEBUG("Started Ranch"), %% Failures will throw exceptions _ = boot_listeners(fun boot_tcp/2, application:get_env(rabbit, num_tcp_acceptors, 10), application:get_env(rabbit, num_conns_sups, 1), "TCP"), @@ -103,7 +104,7 @@ boot_listeners(Fun, NumAcceptors, ConcurrentConnsSupsCount, Type) -> ok -> ok; {error, {could_not_start_listener, Address, Port, Details}} = Error -> - rabbit_log:error("Failed to start ~ts listener [~ts]:~tp, error: ~tp", + ?LOG_ERROR("Failed to start ~ts listener [~ts]:~tp, error: ~tp", [Type, Address, Port, Details]), throw(Error) end. @@ -156,7 +157,7 @@ tcp_listener_addresses({Host, Port, Family0}) [{IPAddress, Port, Family} || {IPAddress, Family} <- getaddr(Host, Family0)]; tcp_listener_addresses({_Host, Port, _Family0}) -> - rabbit_log:error("invalid port ~tp - not 0..65535", [Port]), + ?LOG_ERROR("invalid port ~tp - not 0..65535", [Port]), throw({error, {invalid_port, Port}}). tcp_listener_addresses_auto(Port) -> @@ -264,7 +265,7 @@ stop_ranch_listener_of_protocol(Protocol) -> case ranch_ref_of_protocol(Protocol) of undefined -> ok; Ref -> - rabbit_log:debug("Stopping Ranch listener for protocol ~ts", [Protocol]), + ?LOG_DEBUG("Stopping Ranch listener for protocol ~ts", [Protocol]), ranch:stop_listener(Ref) end. @@ -404,7 +405,7 @@ epmd_port_please(Name, Host) -> epmd_port_please(Name, Host, 0) -> maybe_get_epmd_port(Name, Host); epmd_port_please(Name, Host, RetriesLeft) -> - rabbit_log:debug("Getting epmd port node '~ts', ~b retries left", + ?LOG_DEBUG("Getting epmd port node '~ts', ~b retries left", [Name, RetriesLeft]), case catch maybe_get_epmd_port(Name, Host) of ok -> ok; @@ -520,11 +521,11 @@ emit_connection_info_local(Items, Ref, AggregatorPid) -> -spec close_connection(pid(), string()) -> 'ok'. close_connection(Pid, Explanation) -> - rabbit_log:info("Closing connection ~tp because ~tp", + ?LOG_INFO("Closing connection ~tp because ~tp", [Pid, Explanation]), try rabbit_reader:shutdown(Pid, Explanation) catch exit:{Reason, _Location} -> - rabbit_log:warning("Could not close connection ~tp (reason: ~tp): ~p", + ?LOG_WARNING("Could not close connection ~tp (reason: ~tp): ~p", [Pid, Explanation, Reason]) end. @@ -561,7 +562,7 @@ failed_to_recv_proxy_header(Ref, Error) -> closed -> "error when receiving proxy header: TCP socket was ~tp prematurely"; _Other -> "error when receiving proxy header: ~tp" end, - rabbit_log:debug(Msg, [Error]), + ?LOG_DEBUG(Msg, [Error]), % The following call will clean up resources then exit _ = try ranch:handshake(Ref) catch _:_ -> ok @@ -602,7 +603,7 @@ ranch_handshake(Ref) -> exit:{shutdown, {Reason, {PeerIp, PeerPort}}} = Error:Stacktrace -> PeerAddress = io_lib:format("~ts:~tp", [rabbit_misc:ntoab(PeerIp), PeerPort]), Protocol = ranch_ref_to_protocol(Ref), - rabbit_log:error("~p error during handshake for protocol ~p and peer ~ts", + ?LOG_ERROR("~p error during handshake for protocol ~p and peer ~ts", [Reason, Protocol, PeerAddress]), erlang:raise(exit, Error, Stacktrace) end. @@ -664,7 +665,7 @@ gethostaddr(Host, Family) -> -spec host_lookup_error(_, _) -> no_return(). host_lookup_error(Host, Reason) -> - rabbit_log:error("invalid host ~tp - ~tp", [Host, Reason]), + ?LOG_ERROR("invalid host ~tp - ~tp", [Host, Reason]), throw({error, {invalid_host, Host, Reason}}). resolve_family({_,_,_,_}, auto) -> inet; diff --git a/deps/rabbit/src/rabbit_node_monitor.erl b/deps/rabbit/src/rabbit_node_monitor.erl index 08868633fa03..1fa3943e5eed 100644 --- a/deps/rabbit/src/rabbit_node_monitor.erl +++ b/deps/rabbit/src/rabbit_node_monitor.erl @@ -7,6 +7,9 @@ -module(rabbit_node_monitor). +-include_lib("kernel/include/logger.hrl"). + + -behaviour(gen_server). -export([start_link/0]). @@ -492,14 +495,14 @@ handle_cast({check_partial_partition, Node, Rep, NodeGUID, MyGUID, RepGUID}, case rpc:call(Node, erlang, system_info, [creation]) of {badrpc, _} -> ok; NodeGUID -> - rabbit_log:warning("Received a 'DOWN' message" + ?LOG_WARNING("Received a 'DOWN' message" " from ~tp but still can" " communicate with it ", [Node]), cast(Rep, {partial_partition, Node, node(), RepGUID}); _ -> - rabbit_log:warning("Node ~tp was restarted", [Node]), + ?LOG_WARNING("Node ~tp was restarted", [Node]), ok end end), @@ -530,7 +533,7 @@ handle_cast({partial_partition, NotReallyDown, Proxy, MyGUID}, ArgsBase = [NotReallyDown, Proxy, NotReallyDown], case application:get_env(rabbit, cluster_partition_handling) of {ok, pause_minority} -> - rabbit_log:error( + ?LOG_ERROR( FmtBase ++ " * pause_minority mode enabled~n" "We will therefore pause until the *entire* cluster recovers", ArgsBase), @@ -538,17 +541,17 @@ handle_cast({partial_partition, NotReallyDown, Proxy, MyGUID}, {noreply, State}; {ok, {pause_if_all_down, PreferredNodes, _}} -> case in_preferred_partition(PreferredNodes) of - true -> rabbit_log:error( + true -> ?LOG_ERROR( FmtBase ++ "We will therefore intentionally " "disconnect from ~ts", ArgsBase ++ [Proxy]), upgrade_to_full_partition(Proxy); - false -> rabbit_log:info( + false -> ?LOG_INFO( FmtBase ++ "We are about to pause, no need " "for further actions", ArgsBase) end, {noreply, State}; {ok, _} -> - rabbit_log:error( + ?LOG_ERROR( FmtBase ++ "We will therefore intentionally disconnect from ~ts", ArgsBase ++ [Proxy]), upgrade_to_full_partition(Proxy), @@ -562,7 +565,7 @@ handle_cast({partial_partition, _GUID, _Reporter, _Proxy}, State) -> %% messages reliably when another node disconnects from us. Therefore %% we are told just before the disconnection so we can reciprocate. handle_cast({partial_partition_disconnect, Other}, State) -> - rabbit_log:error("Partial partition disconnect from ~ts", [Other]), + ?LOG_ERROR("Partial partition disconnect from ~ts", [Other]), disconnect(Other), {noreply, State}; @@ -571,7 +574,7 @@ handle_cast({partial_partition_disconnect, Other}, State) -> %% mnesia propagation. handle_cast({node_up, Node, NodeType}, State = #state{monitors = Monitors}) -> - rabbit_log:info("rabbit on node ~tp up", [Node]), + ?LOG_INFO("rabbit on node ~tp up", [Node]), case rabbit_khepri:is_enabled() of true -> ok; @@ -606,7 +609,7 @@ handle_cast({joined_cluster, Node, NodeType}, State) -> end, RunningNodes}) end, - rabbit_log:debug("Node '~tp' has joined the cluster", [Node]), + ?LOG_DEBUG("Node '~tp' has joined the cluster", [Node]), rabbit_event:notify(node_added, [{node, Node}]), {noreply, State}; @@ -634,7 +637,7 @@ handle_cast(_Msg, State) -> handle_info({'DOWN', _MRef, process, {rabbit, Node}, _Reason}, State = #state{monitors = Monitors, subscribers = Subscribers}) -> - rabbit_log:info("rabbit on node ~tp down", [Node]), + ?LOG_INFO("rabbit on node ~tp down", [Node]), case rabbit_khepri:is_enabled() of true -> ok; @@ -653,7 +656,7 @@ handle_info({'DOWN', _MRef, process, Pid, _Reason}, {noreply, State#state{subscribers = pmon:erase(Pid, Subscribers)}}; handle_info({nodedown, Node, Info}, State) -> - rabbit_log:info("node ~tp down: ~tp", + ?LOG_INFO("node ~tp down: ~tp", [Node, proplists:get_value(nodedown_reason, Info)]), case rabbit_khepri:is_enabled() of true -> {noreply, State}; @@ -661,7 +664,7 @@ handle_info({nodedown, Node, Info}, State) -> end; handle_info({nodeup, Node, _Info}, State) -> - rabbit_log:info("node ~tp up", [Node]), + ?LOG_INFO("node ~tp up", [Node]), {noreply, State}; handle_info({mnesia_system_event, @@ -781,13 +784,13 @@ handle_dead_node(Node, State = #state{autoheal = Autoheal}) -> {ok, autoheal} -> State#state{autoheal = rabbit_autoheal:node_down(Node, Autoheal)}; {ok, Term} -> - rabbit_log:warning("cluster_partition_handling ~tp unrecognised, " + ?LOG_WARNING("cluster_partition_handling ~tp unrecognised, " "assuming 'ignore'", [Term]), State end. await_cluster_recovery(Condition) -> - rabbit_log:warning("Cluster minority/secondary status detected - " + ?LOG_WARNING("Cluster minority/secondary status detected - " "awaiting recovery", []), run_outside_applications(fun () -> rabbit:stop(), @@ -838,7 +841,7 @@ do_run_outside_app_fun(Fun) -> try Fun() catch _:E:Stacktrace -> - rabbit_log:error( + ?LOG_ERROR( "rabbit_outside_app_process:~n~tp~n~tp", [E, Stacktrace]) end. @@ -1048,14 +1051,14 @@ possibly_partitioned_nodes() -> alive_rabbit_nodes() -- rabbit_mnesia:cluster_nodes(running). startup_log() -> - rabbit_log:info("Starting rabbit_node_monitor (partition handling strategy unapplicable with Khepri)", []). + ?LOG_INFO("Starting rabbit_node_monitor (partition handling strategy unapplicable with Khepri)", []). startup_log(Nodes) -> {ok, M} = application:get_env(rabbit, cluster_partition_handling), startup_log(Nodes, M). startup_log([], PartitionHandling) -> - rabbit_log:info("Starting rabbit_node_monitor (in ~tp mode)", [PartitionHandling]); + ?LOG_INFO("Starting rabbit_node_monitor (in ~tp mode)", [PartitionHandling]); startup_log(Nodes, PartitionHandling) -> - rabbit_log:info("Starting rabbit_node_monitor (in ~tp mode), might be partitioned from ~tp", + ?LOG_INFO("Starting rabbit_node_monitor (in ~tp mode), might be partitioned from ~tp", [PartitionHandling, Nodes]). diff --git a/deps/rabbit/src/rabbit_nodes.erl b/deps/rabbit/src/rabbit_nodes.erl index 086c386f6b3f..956239c6a175 100644 --- a/deps/rabbit/src/rabbit_nodes.erl +++ b/deps/rabbit/src/rabbit_nodes.erl @@ -126,7 +126,7 @@ seed_internal_cluster_id() -> case rabbit_runtime_parameters:lookup_global(?INTERNAL_CLUSTER_ID_PARAM_NAME) of not_found -> Id = rabbit_guid:binary(rabbit_guid:gen(), "rabbitmq-cluster-id"), - rabbit_log:info("Initialising internal cluster ID to '~ts'", [Id]), + ?LOG_INFO("Initialising internal cluster ID to '~ts'", [Id]), rabbit_runtime_parameters:set_global(?INTERNAL_CLUSTER_ID_PARAM_NAME, Id, ?INTERNAL_USER), Id; Param -> @@ -138,7 +138,7 @@ seed_user_provided_cluster_name() -> case application:get_env(rabbit, cluster_name) of undefined -> ok; {ok, Name} -> - rabbit_log:info("Setting cluster name to '~ts' as configured", [Name]), + ?LOG_INFO("Setting cluster name to '~ts' as configured", [Name]), set_cluster_name(rabbit_data_coercion:to_binary(Name)) end. diff --git a/deps/rabbit/src/rabbit_peer_discovery_classic_config.erl b/deps/rabbit/src/rabbit_peer_discovery_classic_config.erl index c22570d5c1f0..b0b9d31bd249 100644 --- a/deps/rabbit/src/rabbit_peer_discovery_classic_config.erl +++ b/deps/rabbit/src/rabbit_peer_discovery_classic_config.erl @@ -6,6 +6,9 @@ %% -module(rabbit_peer_discovery_classic_config). + +-include_lib("kernel/include/logger.hrl"). + -behaviour(rabbit_peer_discovery_backend). -export([list_nodes/0, supports_registration/0, register/0, unregister/0, @@ -42,7 +45,7 @@ check_duplicates(Nodes) -> true -> ok; false -> - rabbit_log:warning("Classic peer discovery backend: list of " + ?LOG_WARNING("Classic peer discovery backend: list of " "nodes contains duplicates ~0tp", [Nodes]) end. @@ -52,7 +55,7 @@ check_local_node(Nodes) -> true -> ok; false -> - rabbit_log:warning("Classic peer discovery backend: list of " + ?LOG_WARNING("Classic peer discovery backend: list of " "nodes does not contain the local node ~0tp", [Nodes]) end. @@ -65,7 +68,7 @@ lock(Nodes) -> Node = node(), case lists:member(Node, Nodes) of false when Nodes =/= [] -> - rabbit_log:warning("Local node ~ts is not part of configured nodes ~tp. " + ?LOG_WARNING("Local node ~ts is not part of configured nodes ~tp. " "This might lead to incorrect cluster formation.", [Node, Nodes]); _ -> ok end, diff --git a/deps/rabbit/src/rabbit_peer_discovery_dns.erl b/deps/rabbit/src/rabbit_peer_discovery_dns.erl index ac898e2a21c8..b7e75aa78d4d 100644 --- a/deps/rabbit/src/rabbit_peer_discovery_dns.erl +++ b/deps/rabbit/src/rabbit_peer_discovery_dns.erl @@ -6,6 +6,9 @@ %% -module(rabbit_peer_discovery_dns). + +-include_lib("kernel/include/logger.hrl"). + -behaviour(rabbit_peer_discovery_backend). -export([list_nodes/0, supports_registration/0, register/0, unregister/0, @@ -27,7 +30,7 @@ list_nodes() -> {ok, ClusterFormation} -> case proplists:get_value(peer_discovery_dns, ClusterFormation) of undefined -> - rabbit_log:warning("Peer discovery backend is set to ~ts " + ?LOG_WARNING("Peer discovery backend is set to ~ts " "but final config does not contain rabbit.cluster_formation.peer_discovery_dns. " "Cannot discover any nodes because seed hostname is not configured!", [?MODULE]), @@ -90,7 +93,7 @@ decode_record(ipv6) -> lookup(SeedHostname, LongNamesUsed, IPv) -> IPs = inet_res:lookup(SeedHostname, in, decode_record(IPv)), - rabbit_log:info("Addresses discovered via ~ts records of ~ts: ~ts", + ?LOG_INFO("Addresses discovered via ~ts records of ~ts: ~ts", [string:to_upper(atom_to_list(decode_record(IPv))), SeedHostname, string:join([inet_parse:ntoa(IP) || IP <- IPs], ", ")]), @@ -106,6 +109,6 @@ extract_host({ok, {hostent, FQDN, _, _, _, _}}, true, _Address) -> extract_host({ok, {hostent, FQDN, _, _, _, _}}, false, _Address) -> lists:nth(1, string:tokens(FQDN, ".")); extract_host({error, Error}, _, Address) -> - rabbit_log:error("Reverse DNS lookup for address ~ts failed: ~tp", + ?LOG_ERROR("Reverse DNS lookup for address ~ts failed: ~tp", [inet_parse:ntoa(Address), Error]), error. diff --git a/deps/rabbit/src/rabbit_plugins.erl b/deps/rabbit/src/rabbit_plugins.erl index 439595fde57c..086adae50998 100644 --- a/deps/rabbit/src/rabbit_plugins.erl +++ b/deps/rabbit/src/rabbit_plugins.erl @@ -7,6 +7,7 @@ -module(rabbit_plugins). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([setup/0, active/0, read_enabled/1, list/1, list/2, dependencies/3, running_plugins/0]). -export([ensure/1]). -export([validate_plugins/1, format_invalid_plugins/1]). @@ -54,13 +55,13 @@ ensure1(FileJustChanged0) -> {[], []} -> ok; {[], _} -> - rabbit_log:info("Plugins changed; disabled ~tp", + ?LOG_INFO("Plugins changed; disabled ~tp", [Stop]); {_, []} -> - rabbit_log:info("Plugins changed; enabled ~tp", + ?LOG_INFO("Plugins changed; enabled ~tp", [Start]); {_, _} -> - rabbit_log:info("Plugins changed; enabled ~tp, disabled ~tp", + ?LOG_INFO("Plugins changed; enabled ~tp, disabled ~tp", [Start, Stop]) end, {ok, Start, Stop}; @@ -271,7 +272,7 @@ maybe_warn_about_invalid_plugins([]) -> ok; maybe_warn_about_invalid_plugins(InvalidPlugins) -> %% TODO: error message formatting - rabbit_log:warning(format_invalid_plugins(InvalidPlugins)). + ?LOG_WARNING(format_invalid_plugins(InvalidPlugins)). format_invalid_plugins(InvalidPlugins) -> @@ -327,7 +328,7 @@ validate_plugins(Plugins, BrokerVersion) -> true -> case BrokerVersion of "0.0.0" -> - rabbit_log:warning( + ?LOG_WARNING( "Running development version of the broker." " Requirement ~tp for plugin ~tp is ignored.", [BrokerVersionReqs, Name]); @@ -358,7 +359,7 @@ check_plugins_versions(PluginName, AllPlugins, RequiredVersions) -> true -> case Version of "" -> - rabbit_log:warning( + ?LOG_WARNING( "~tp plugin version is not defined." " Requirement ~tp for plugin ~tp is ignored", [Name, Versions, PluginName]); @@ -426,7 +427,7 @@ prepare_dir_plugin(PluginAppDescPath) -> {module, _} -> ok; {error, badfile} -> - rabbit_log:error("Failed to enable plugin \"~ts\": " + ?LOG_ERROR("Failed to enable plugin \"~ts\": " "it may have been built with an " "incompatible (more recent?) " "version of Erlang", [Plugin]), @@ -459,11 +460,11 @@ prepare_plugin(#plugin{type = ez, name = Name, location = Location}, ExpandDir) [PluginAppDescPath|_] -> prepare_dir_plugin(PluginAppDescPath); _ -> - rabbit_log:error("Plugin archive '~ts' doesn't contain an .app file", [Location]), + ?LOG_ERROR("Plugin archive '~ts' doesn't contain an .app file", [Location]), throw({app_file_missing, Name, Location}) end; {error, Reason} -> - rabbit_log:error("Could not unzip plugin archive '~ts': ~tp", [Location, Reason]), + ?LOG_ERROR("Could not unzip plugin archive '~ts': ~tp", [Location, Reason]), throw({failed_to_unzip_plugin, Name, Location, Reason}) end; prepare_plugin(#plugin{type = dir, location = Location, name = Name}, @@ -472,7 +473,7 @@ prepare_plugin(#plugin{type = dir, location = Location, name = Name}, [PluginAppDescPath|_] -> prepare_dir_plugin(PluginAppDescPath); _ -> - rabbit_log:error("Plugin directory '~ts' doesn't contain an .app file", [Location]), + ?LOG_ERROR("Plugin directory '~ts' doesn't contain an .app file", [Location]), throw({app_file_missing, Name, Location}) end. @@ -668,12 +669,12 @@ remove_plugins(Plugins) -> lists:member(Name, PluginDeps), if IsOTPApp -> - rabbit_log:debug( + ?LOG_DEBUG( "Plugins discovery: " "ignoring ~ts, Erlang/OTP application", [Name]); not IsAPlugin -> - rabbit_log:debug( + ?LOG_DEBUG( "Plugins discovery: " "ignoring ~ts, not a RabbitMQ plugin", [Name]); diff --git a/deps/rabbit/src/rabbit_policy.erl b/deps/rabbit/src/rabbit_policy.erl index 4c313528fd03..8cb2afcf4b6f 100644 --- a/deps/rabbit/src/rabbit_policy.erl +++ b/deps/rabbit/src/rabbit_policy.erl @@ -29,6 +29,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include("amqqueue.hrl"). +-include_lib("kernel/include/logger.hrl"). -import(rabbit_misc, [pget/2, pget/3]). @@ -285,7 +286,7 @@ parse_set0(Type, VHost, Name, Pattern, Defn, Priority, ApplyTo, ActingUser) -> {<<"priority">>, Priority}, {<<"apply-to">>, ApplyTo}], ActingUser), - rabbit_log:info("Successfully set policy '~ts' matching ~ts names in virtual host '~ts' using pattern '~ts'", + ?LOG_INFO("Successfully set policy '~ts' matching ~ts names in virtual host '~ts' using pattern '~ts'", [Name, ApplyTo, VHost, Pattern]), R; {error, Reason} -> diff --git a/deps/rabbit/src/rabbit_priority_queue.erl b/deps/rabbit/src/rabbit_priority_queue.erl index e83181aebd8d..33657daa631a 100644 --- a/deps/rabbit/src/rabbit_priority_queue.erl +++ b/deps/rabbit/src/rabbit_priority_queue.erl @@ -9,6 +9,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include("amqqueue.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(rabbit_backing_queue). @@ -66,7 +67,7 @@ enable() -> {ok, RealBQ} = application:get_env(rabbit, backing_queue_module), case RealBQ of ?MODULE -> ok; - _ -> rabbit_log:info("Priority queues enabled, real BQ is ~ts", + _ -> ?LOG_INFO("Priority queues enabled, real BQ is ~ts", [RealBQ]), application:set_env( rabbitmq_priority_queue, backing_queue_module, RealBQ), diff --git a/deps/rabbit/src/rabbit_queue_index.erl b/deps/rabbit/src/rabbit_queue_index.erl index 282ba5827228..c8a084bd414a 100644 --- a/deps/rabbit/src/rabbit_queue_index.erl +++ b/deps/rabbit/src/rabbit_queue_index.erl @@ -223,6 +223,7 @@ }). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). %%---------------------------------------------------------------------------- @@ -556,7 +557,7 @@ start(VHost, DurableQueueNames) -> ToDelete = [filename:join([rabbit_vhost:msg_store_dir_path(VHost), "queues", Dir]) || Dir <- lists:subtract(all_queue_directory_names(VHost), sets:to_list(DurableDirectories))], - rabbit_log:debug("Deleting unknown files/folders: ~p", [ToDelete]), + ?LOG_DEBUG("Deleting unknown files/folders: ~p", [ToDelete]), _ = rabbit_file:recursive_delete(ToDelete), rabbit_recovery_terms:clear(VHost), @@ -1182,7 +1183,7 @@ load_segment(KeepAcked, #segment { path = Path }) -> %% was missing above). We also log some information. case SegBin of <<0:Size/unit:8>> -> - rabbit_log:warning("Deleting invalid v1 segment file ~ts (file only contains NUL bytes)", + ?LOG_WARNING("Deleting invalid v1 segment file ~ts (file only contains NUL bytes)", [Path]), _ = rabbit_file:delete(Path), Empty; diff --git a/deps/rabbit/src/rabbit_queue_type.erl b/deps/rabbit/src/rabbit_queue_type.erl index c095fc4dfe96..936bffc69c23 100644 --- a/deps/rabbit/src/rabbit_queue_type.erl +++ b/deps/rabbit/src/rabbit_queue_type.erl @@ -14,6 +14,7 @@ -include("vhost.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). -include_lib("amqp10_common/include/amqp10_types.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([ init/0, @@ -554,7 +555,7 @@ recover(VHost, Qs) -> end, ByType0, Qs), maps:fold(fun (Mod, Queues, {R0, F0}) -> {Taken, {R, F}} = timer:tc(Mod, recover, [VHost, Queues]), - rabbit_log:info("Recovering ~b queues of type ~ts took ~bms", + ?LOG_INFO("Recovering ~b queues of type ~ts took ~bms", [length(Queues), Mod, Taken div 1000]), {R0 ++ R, F0 ++ F} end, {[], []}, ByType). diff --git a/deps/rabbit/src/rabbit_quorum_queue.erl b/deps/rabbit/src/rabbit_quorum_queue.erl index 4e192df874f5..5cf33fbde0db 100644 --- a/deps/rabbit/src/rabbit_quorum_queue.erl +++ b/deps/rabbit/src/rabbit_quorum_queue.erl @@ -106,6 +106,7 @@ -include_lib("stdlib/include/qlc.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). -include("amqqueue.hrl"). +-include_lib("kernel/include/logger.hrl"). -rabbit_boot_step( {rabbit_quorum_queue_type, @@ -129,7 +130,7 @@ -define(DEFAULT_DELIVERY_LIMIT, 20). -define(INFO(Str, Args), - rabbit_log:info("[~s:~s/~b] " Str, + ?LOG_INFO("[~s:~s/~b] " Str, [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY | Args])). @@ -284,7 +285,7 @@ start_cluster(Q) -> ?RPC_TIMEOUT)], MinVersion = lists:min([rabbit_fifo:version() | Versions]), - rabbit_log:debug("Will start up to ~w replicas for quorum queue ~ts with " + ?LOG_DEBUG("Will start up to ~w replicas for quorum queue ~ts with " "leader on node '~ts', initial machine version ~b", [QuorumSize, rabbit_misc:rs(QName), LeaderNode, MinVersion]), case rabbit_amqqueue:internal_declare(NewQ1, false) of @@ -354,7 +355,7 @@ gather_policy_config(Q, IsQueueDeclaration) -> undefined -> case IsQueueDeclaration of true -> - rabbit_log:info( + ?LOG_INFO( "~ts: delivery_limit not set, defaulting to ~b", [rabbit_misc:rs(QName), ?DEFAULT_DELIVERY_LIMIT]); false -> @@ -660,7 +661,7 @@ handle_tick(QName, ok -> ok; repaired -> - rabbit_log:debug("Repaired quorum queue ~ts amqqueue record", + ?LOG_DEBUG("Repaired quorum queue ~ts amqqueue record", [rabbit_misc:rs(QName)]) end, ExpectedNodes = rabbit_nodes:list_members(), @@ -670,7 +671,7 @@ handle_tick(QName, Stale when length(ExpectedNodes) > 0 -> %% rabbit_nodes:list_members/0 returns [] when there %% is an error so we need to handle that case - rabbit_log:debug("~ts: stale nodes detected in quorum " + ?LOG_DEBUG("~ts: stale nodes detected in quorum " "queue state. Purging ~w", [rabbit_misc:rs(QName), Stale]), %% pipeline purge command @@ -684,13 +685,13 @@ handle_tick(QName, ok catch _:Err -> - rabbit_log:debug("~ts: handle tick failed with ~p", + ?LOG_DEBUG("~ts: handle tick failed with ~p", [rabbit_misc:rs(QName), Err]), ok end end); handle_tick(QName, Config, _Nodes) -> - rabbit_log:debug("~ts: handle tick received unexpected config format ~tp", + ?LOG_DEBUG("~ts: handle tick received unexpected config format ~tp", [rabbit_misc:rs(QName), Config]). repair_leader_record(Q, Name) -> @@ -701,7 +702,7 @@ repair_leader_record(Q, Name) -> ok; _ -> QName = amqqueue:get_name(Q), - rabbit_log:debug("~ts: updating leader record to current node ~ts", + ?LOG_DEBUG("~ts: updating leader record to current node ~ts", [rabbit_misc:rs(QName), Node]), ok = become_leader0(QName, Name), ok @@ -776,7 +777,7 @@ maybe_apply_policies(Q, #{config := CurrentConfig}) -> ShouldUpdate = NewPolicyConfig =/= CurrentPolicyConfig, case ShouldUpdate of true -> - rabbit_log:debug("Re-applying policies to ~ts", [rabbit_misc:rs(amqqueue:get_name(Q))]), + ?LOG_DEBUG("Re-applying policies to ~ts", [rabbit_misc:rs(amqqueue:get_name(Q))]), policy_changed(Q), ok; false -> ok @@ -798,7 +799,7 @@ recover(_Vhost, Queues) -> {error, Err1} when Err1 == not_started orelse Err1 == name_not_registered -> - rabbit_log:warning("Quorum queue recovery: configured member of ~ts was not found on this node. Starting member as a new one. " + ?LOG_WARNING("Quorum queue recovery: configured member of ~ts was not found on this node. Starting member as a new one. " "Context: ~s", [rabbit_misc:rs(QName), Err1]), % queue was never started on this node @@ -806,7 +807,7 @@ recover(_Vhost, Queues) -> case start_server(make_ra_conf(Q0, ServerId)) of ok -> ok; Err2 -> - rabbit_log:warning("recover: quorum queue ~w could not" + ?LOG_WARNING("recover: quorum queue ~w could not" " be started ~w", [Name, Err2]), fail end; @@ -817,7 +818,7 @@ recover(_Vhost, Queues) -> ok; Err -> %% catch all clause to avoid causing the vhost not to start - rabbit_log:warning("recover: quorum queue ~w could not be " + ?LOG_WARNING("recover: quorum queue ~w could not be " "restarted ~w", [Name, Err]), fail end, @@ -908,7 +909,7 @@ delete(Q, _IfUnused, _IfEmpty, ActingUser) when ?amqqueue_is_quorum(Q) -> ok; false -> %% attempt forced deletion of all servers - rabbit_log:warning( + ?LOG_WARNING( "Could not delete quorum '~ts', not enough nodes " " online to reach a quorum: ~255p." " Attempting force delete.", @@ -929,7 +930,7 @@ force_delete_queue(Servers) -> case catch(ra:force_delete_server(?RA_SYSTEM, S)) of ok -> ok; Err -> - rabbit_log:warning( + ?LOG_WARNING( "Force delete of ~w failed with: ~w" "This may require manual data clean up", [S, Err]), @@ -1222,7 +1223,7 @@ policy_changed(Q) -> ok; Err -> FormattedQueueName = rabbit_misc:rs(amqqueue:get_name(Q)), - rabbit_log:warning("~s: policy may not have been successfully applied. Error: ~p", + ?LOG_WARNING("~s: policy may not have been successfully applied. Error: ~p", [FormattedQueueName, Err]), ok end. @@ -1340,7 +1341,7 @@ add_member(VHost, Name, Node, Membership, Timeout) is_binary(Name) andalso is_atom(Node) -> QName = #resource{virtual_host = VHost, name = Name, kind = queue}, - rabbit_log:debug("Asked to add a replica for queue ~ts on node ~ts", + ?LOG_DEBUG("Asked to add a replica for queue ~ts on node ~ts", [rabbit_misc:rs(QName), Node]), case rabbit_amqqueue:lookup(QName) of {ok, Q} when ?amqqueue_is_classic(Q) -> @@ -1354,7 +1355,7 @@ add_member(VHost, Name, Node, Membership, Timeout) case lists:member(Node, QNodes) of true -> %% idempotent by design - rabbit_log:debug("Quorum ~ts already has a replica on node ~ts", + ?LOG_DEBUG("Quorum ~ts already has a replica on node ~ts", [rabbit_misc:rs(QName), Node]), ok; false -> @@ -1422,7 +1423,7 @@ do_add_member(Q, Node, Membership, Timeout) {erlang, is_list, []}, #{condition => {applied, {RaIndex, RaTerm}}}), _ = rabbit_amqqueue:update(QName, Fun), - rabbit_log:info("Added a replica of quorum ~ts on node ~ts", [rabbit_misc:rs(QName), Node]), + ?LOG_INFO("Added a replica of quorum ~ts on node ~ts", [rabbit_misc:rs(QName), Node]), ok; {timeout, _} -> _ = ra:force_delete_server(?RA_SYSTEM, ServerId), @@ -1433,7 +1434,7 @@ do_add_member(Q, Node, Membership, Timeout) E end; E -> - rabbit_log:warning("Could not add a replica of quorum ~ts on node ~ts: ~p", + ?LOG_WARNING("Could not add a replica of quorum ~ts on node ~ts: ~p", [rabbit_misc:rs(QName), Node, E]), E end. @@ -1484,7 +1485,7 @@ delete_member(Q, Node) when ?amqqueue_is_quorum(Q) -> _ = rabbit_amqqueue:update(QName, Fun), case ra:force_delete_server(?RA_SYSTEM, ServerId) of ok -> - rabbit_log:info("Deleted a replica of quorum ~ts on node ~ts", [rabbit_misc:rs(QName), Node]), + ?LOG_INFO("Deleted a replica of quorum ~ts on node ~ts", [rabbit_misc:rs(QName), Node]), ok; {error, {badrpc, nodedown}} -> ok; @@ -1507,10 +1508,10 @@ delete_member(Q, Node) when ?amqqueue_is_quorum(Q) -> [{rabbit_amqqueue:name(), {ok, pos_integer()} | {error, pos_integer(), term()}}]. shrink_all(Node) -> - rabbit_log:info("Asked to remove all quorum queue replicas from node ~ts", [Node]), + ?LOG_INFO("Asked to remove all quorum queue replicas from node ~ts", [Node]), [begin QName = amqqueue:get_name(Q), - rabbit_log:info("~ts: removing member (replica) on node ~w", + ?LOG_INFO("~ts: removing member (replica) on node ~w", [rabbit_misc:rs(QName), Node]), Size = length(get_nodes(Q)), case delete_member(Q, Node) of @@ -1520,7 +1521,7 @@ shrink_all(Node) -> %% this could be timing related and due to a new leader just being %% elected but it's noop command not been committed yet. %% lets sleep and retry once - rabbit_log:info("~ts: failed to remove member (replica) on node ~w " + ?LOG_INFO("~ts: failed to remove member (replica) on node ~w " "as cluster change is not permitted. " "retrying once in 500ms", [rabbit_misc:rs(QName), Node]), @@ -1529,12 +1530,12 @@ shrink_all(Node) -> ok -> {QName, {ok, Size-1}}; {error, Err} -> - rabbit_log:warning("~ts: failed to remove member (replica) on node ~w, error: ~w", + ?LOG_WARNING("~ts: failed to remove member (replica) on node ~w, error: ~w", [rabbit_misc:rs(QName), Node, Err]), {QName, {error, Size, Err}} end; {error, Err} -> - rabbit_log:warning("~ts: failed to remove member (replica) on node ~w, error: ~w", + ?LOG_WARNING("~ts: failed to remove member (replica) on node ~w, error: ~w", [rabbit_misc:rs(QName), Node, Err]), {QName, {error, Size, Err}} end @@ -1554,13 +1555,13 @@ grow(Node, VhostSpec, QueueSpec, Strategy, Membership) -> [begin Size = length(get_nodes(Q)), QName = amqqueue:get_name(Q), - rabbit_log:info("~ts: adding a new member (replica) on node ~w", + ?LOG_INFO("~ts: adding a new member (replica) on node ~w", [rabbit_misc:rs(QName), Node]), case add_member(Q, Node, Membership) of ok -> {QName, {ok, Size + 1}}; {error, Err} -> - rabbit_log:warning( + ?LOG_WARNING( "~ts: failed to add member (replica) on node ~w, error: ~w", [rabbit_misc:rs(QName), Node, Err]), {QName, {error, Size, Err}} @@ -1647,19 +1648,19 @@ dead_letter_handler(Q, Overflow) -> dlh(undefined, undefined, undefined, _, _) -> undefined; dlh(undefined, RoutingKey, undefined, _, QName) -> - rabbit_log:warning("Disabling dead-lettering for ~ts despite configured dead-letter-routing-key '~ts' " + ?LOG_WARNING("Disabling dead-lettering for ~ts despite configured dead-letter-routing-key '~ts' " "because dead-letter-exchange is not configured.", [rabbit_misc:rs(QName), RoutingKey]), undefined; dlh(undefined, _, Strategy, _, QName) -> - rabbit_log:warning("Disabling dead-lettering for ~ts despite configured dead-letter-strategy '~ts' " + ?LOG_WARNING("Disabling dead-lettering for ~ts despite configured dead-letter-strategy '~ts' " "because dead-letter-exchange is not configured.", [rabbit_misc:rs(QName), Strategy]), undefined; dlh(_, _, <<"at-least-once">>, reject_publish, _) -> at_least_once; dlh(Exchange, RoutingKey, <<"at-least-once">>, drop_head, QName) -> - rabbit_log:warning("Falling back to dead-letter-strategy at-most-once for ~ts " + ?LOG_WARNING("Falling back to dead-letter-strategy at-most-once for ~ts " "because configured dead-letter-strategy at-least-once is incompatible with " "effective overflow strategy drop-head. To enable dead-letter-strategy " "at-least-once, set overflow strategy to reject-publish.", @@ -2030,7 +2031,7 @@ overflow(undefined, Def, _QName) -> Def; overflow(<<"reject-publish">>, _Def, _QName) -> reject_publish; overflow(<<"drop-head">>, _Def, _QName) -> drop_head; overflow(<<"reject-publish-dlx">> = V, Def, QName) -> - rabbit_log:warning("Invalid overflow strategy ~tp for quorum queue: ~ts", + ?LOG_WARNING("Invalid overflow strategy ~tp for quorum queue: ~ts", [V, rabbit_misc:rs(QName)]), Def. @@ -2069,7 +2070,7 @@ force_shrink_member_to_current_member(VHost, Name) -> Node = node(), QName = rabbit_misc:r(VHost, queue, Name), QNameFmt = rabbit_misc:rs(QName), - rabbit_log:warning("Shrinking ~ts to a single node: ~ts", [QNameFmt, Node]), + ?LOG_WARNING("Shrinking ~ts to a single node: ~ts", [QNameFmt, Node]), case rabbit_amqqueue:lookup(QName) of {ok, Q} when ?is_amqqueue(Q) -> {RaName, _} = amqqueue:get_pid(Q), @@ -2082,19 +2083,19 @@ force_shrink_member_to_current_member(VHost, Name) -> end, _ = rabbit_amqqueue:update(QName, Fun), _ = [ra:force_delete_server(?RA_SYSTEM, {RaName, N}) || N <- OtherNodes], - rabbit_log:warning("Shrinking ~ts finished", [QNameFmt]); + ?LOG_WARNING("Shrinking ~ts finished", [QNameFmt]); _ -> - rabbit_log:warning("Shrinking failed, ~ts not found", [QNameFmt]), + ?LOG_WARNING("Shrinking failed, ~ts not found", [QNameFmt]), {error, not_found} end. force_vhost_queues_shrink_member_to_current_member(VHost) when is_binary(VHost) -> - rabbit_log:warning("Shrinking all quorum queues in vhost '~ts' to a single node: ~ts", [VHost, node()]), + ?LOG_WARNING("Shrinking all quorum queues in vhost '~ts' to a single node: ~ts", [VHost, node()]), ListQQs = fun() -> rabbit_amqqueue:list(VHost) end, force_all_queues_shrink_member_to_current_member(ListQQs). force_all_queues_shrink_member_to_current_member() -> - rabbit_log:warning("Shrinking all quorum queues to a single node: ~ts", [node()]), + ?LOG_WARNING("Shrinking all quorum queues to a single node: ~ts", [node()]), ListQQs = fun() -> rabbit_amqqueue:list() end, force_all_queues_shrink_member_to_current_member(ListQQs). @@ -2104,7 +2105,7 @@ force_all_queues_shrink_member_to_current_member(ListQQFun) when is_function(Lis QName = amqqueue:get_name(Q), {RaName, _} = amqqueue:get_pid(Q), OtherNodes = lists:delete(Node, get_nodes(Q)), - rabbit_log:warning("Shrinking queue ~ts to a single node: ~ts", [rabbit_misc:rs(QName), Node]), + ?LOG_WARNING("Shrinking queue ~ts to a single node: ~ts", [rabbit_misc:rs(QName), Node]), ok = ra_server_proc:force_shrink_members_to_current_member({RaName, Node}), Fun = fun (QQ) -> TS0 = amqqueue:get_type_state(QQ), @@ -2114,7 +2115,7 @@ force_all_queues_shrink_member_to_current_member(ListQQFun) when is_function(Lis _ = rabbit_amqqueue:update(QName, Fun), _ = [ra:force_delete_server(?RA_SYSTEM, {RaName, N}) || N <- OtherNodes] end || Q <- ListQQFun(), amqqueue:get_type(Q) == ?MODULE], - rabbit_log:warning("Shrinking finished"), + ?LOG_WARNING("Shrinking finished"), ok. force_checkpoint_on_queue(QName) -> @@ -2124,7 +2125,7 @@ force_checkpoint_on_queue(QName) -> {error, classic_queue_not_supported}; {ok, Q} when ?amqqueue_is_quorum(Q) -> {RaName, _} = amqqueue:get_pid(Q), - rabbit_log:debug("Sending command to force ~ts to take a checkpoint", [QNameFmt]), + ?LOG_DEBUG("Sending command to force ~ts to take a checkpoint", [QNameFmt]), Nodes = amqqueue:get_nodes(Q), _ = [ra:cast_aux_command({RaName, Node}, force_checkpoint) || Node <- Nodes], @@ -2142,7 +2143,7 @@ force_checkpoint(VhostSpec, QueueSpec) -> ok -> {QName, {ok}}; {error, Err} -> - rabbit_log:warning("~ts: failed to force checkpoint, error: ~w", + ?LOG_WARNING("~ts: failed to force checkpoint, error: ~w", [rabbit_misc:rs(QName), Err]), {QName, {error, Err}} end @@ -2274,7 +2275,7 @@ wait_for_leader_health_checks(Ref, N, UnhealthyAcc) -> check_process_limit_safety(QCount, ProcessLimitThreshold) -> case (erlang:system_info(process_count) + QCount) >= ProcessLimitThreshold of true -> - rabbit_log:warning("Leader health check not permitted, process limit threshold will be exceeded."), + ?LOG_WARNING("Leader health check not permitted, process limit threshold will be exceeded."), throw({error, leader_health_check_process_limit_exceeded}); false -> ok @@ -2283,7 +2284,7 @@ check_process_limit_safety(QCount, ProcessLimitThreshold) -> maybe_log_leader_health_check_result([]) -> ok; maybe_log_leader_health_check_result(Result) -> Qs = lists:map(fun(R) -> catch maps:get(<<"readable_name">>, R) end, Result), - rabbit_log:warning("Leader health check result (unhealthy leaders detected): ~tp", [Qs]). + ?LOG_WARNING("Leader health check result (unhealthy leaders detected): ~tp", [Qs]). policy_apply_to_name() -> <<"quorum_queues">>. @@ -2295,52 +2296,52 @@ drain(TransferCandidates) -> ok. transfer_leadership([]) -> - rabbit_log:warning("Skipping leadership transfer of quorum queues: no candidate " + ?LOG_WARNING("Skipping leadership transfer of quorum queues: no candidate " "(online, not under maintenance) nodes to transfer to!"); transfer_leadership(_TransferCandidates) -> %% we only transfer leadership for QQs that have local leaders Queues = rabbit_amqqueue:list_local_leaders(), - rabbit_log:info("Will transfer leadership of ~b quorum queues with current leader on this node", + ?LOG_INFO("Will transfer leadership of ~b quorum queues with current leader on this node", [length(Queues)]), [begin Name = amqqueue:get_name(Q), - rabbit_log:debug("Will trigger a leader election for local quorum queue ~ts", + ?LOG_DEBUG("Will trigger a leader election for local quorum queue ~ts", [rabbit_misc:rs(Name)]), %% we trigger an election and exclude this node from the list of candidates %% by simply shutting its local QQ replica (Ra server) RaLeader = amqqueue:get_pid(Q), - rabbit_log:debug("Will stop Ra server ~tp", [RaLeader]), + ?LOG_DEBUG("Will stop Ra server ~tp", [RaLeader]), case rabbit_quorum_queue:stop_server(RaLeader) of ok -> - rabbit_log:debug("Successfully stopped Ra server ~tp", [RaLeader]); + ?LOG_DEBUG("Successfully stopped Ra server ~tp", [RaLeader]); {error, nodedown} -> - rabbit_log:error("Failed to stop Ra server ~tp: target node was reported as down") + ?LOG_ERROR("Failed to stop Ra server ~tp: target node was reported as down") end end || Q <- Queues], - rabbit_log:info("Leadership transfer for quorum queues hosted on this node has been initiated"). + ?LOG_INFO("Leadership transfer for quorum queues hosted on this node has been initiated"). %% TODO: I just copied it over, it looks like was always called inside maintenance so... -spec stop_local_quorum_queue_followers() -> ok. stop_local_quorum_queue_followers() -> Queues = rabbit_amqqueue:list_local_followers(), - rabbit_log:info("Will stop local follower replicas of ~b quorum queues on this node", + ?LOG_INFO("Will stop local follower replicas of ~b quorum queues on this node", [length(Queues)]), [begin Name = amqqueue:get_name(Q), - rabbit_log:debug("Will stop a local follower replica of quorum queue ~ts", + ?LOG_DEBUG("Will stop a local follower replica of quorum queue ~ts", [rabbit_misc:rs(Name)]), %% shut down Ra nodes so that they are not considered for leader election {RegisteredName, _LeaderNode} = amqqueue:get_pid(Q), RaNode = {RegisteredName, node()}, - rabbit_log:debug("Will stop Ra server ~tp", [RaNode]), + ?LOG_DEBUG("Will stop Ra server ~tp", [RaNode]), case rabbit_quorum_queue:stop_server(RaNode) of ok -> - rabbit_log:debug("Successfully stopped Ra server ~tp", [RaNode]); + ?LOG_DEBUG("Successfully stopped Ra server ~tp", [RaNode]); {error, nodedown} -> - rabbit_log:error("Failed to stop Ra server ~tp: target node was reported as down") + ?LOG_ERROR("Failed to stop Ra server ~tp: target node was reported as down") end end || Q <- Queues], - rabbit_log:info("Stopped all local replicas of quorum queues hosted on this node"). + ?LOG_INFO("Stopped all local replicas of quorum queues hosted on this node"). revive() -> revive_local_queue_members(). @@ -2350,17 +2351,17 @@ revive_local_queue_members() -> %% NB: this function ignores the first argument so we can just pass the %% empty binary as the vhost name. {Recovered, Failed} = rabbit_quorum_queue:recover(<<>>, Queues), - rabbit_log:debug("Successfully revived ~b quorum queue replicas", + ?LOG_DEBUG("Successfully revived ~b quorum queue replicas", [length(Recovered)]), case length(Failed) of 0 -> ok; NumFailed -> - rabbit_log:error("Failed to revive ~b quorum queue replicas", + ?LOG_ERROR("Failed to revive ~b quorum queue replicas", [NumFailed]) end, - rabbit_log:info("Restart of local quorum queue replicas is complete"), + ?LOG_INFO("Restart of local quorum queue replicas is complete"), ok. queue_vm_stats_sups() -> diff --git a/deps/rabbit/src/rabbit_reader.erl b/deps/rabbit/src/rabbit_reader.erl index bbaa79bd0388..78e37a1b90fc 100644 --- a/deps/rabbit/src/rabbit_reader.erl +++ b/deps/rabbit/src/rabbit_reader.erl @@ -43,6 +43,7 @@ -include_lib("rabbit_common/include/rabbit_framing.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). -include("rabbit_amqp_metrics.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([start_link/2, info/2, force_event_refresh/2, shutdown/2]). @@ -1363,7 +1364,7 @@ handle_method0(#'connection.update_secret'{new_secret = NewSecret, reason = Reas %% Any secret update errors coming from the authz backend will be handled in the other branch. %% Therefore we optimistically do no error handling here. MK. lists:foreach(fun(Ch) -> - rabbit_log:debug("Updating user/auth backend state for channel ~tp", [Ch]), + ?LOG_DEBUG("Updating user/auth backend state for channel ~tp", [Ch]), _ = rabbit_channel:update_user_state(Ch, User1) end, all_channels()), ok = send_on_channel0(Sock, #'connection.update_secret_ok'{}, Protocol), @@ -1505,7 +1506,7 @@ auth_phase(Response, auth_state = AuthState, host = RemoteAddress}, sock = Sock}) -> - rabbit_log:debug("Client address during authN phase: ~tp", [RemoteAddress]), + ?LOG_DEBUG("Client address during authN phase: ~tp", [RemoteAddress]), case AuthMechanism:handle_response(Response, AuthState) of {refused, Username, Msg, Args} -> rabbit_core_metrics:auth_attempt_failed(RemoteAddress, Username, amqp091), diff --git a/deps/rabbit/src/rabbit_recovery_terms.erl b/deps/rabbit/src/rabbit_recovery_terms.erl index da77c12a84a8..78b4c214aa0e 100644 --- a/deps/rabbit/src/rabbit_recovery_terms.erl +++ b/deps/rabbit/src/rabbit_recovery_terms.erl @@ -19,6 +19,7 @@ terminate/2, code_change/3]). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). %%---------------------------------------------------------------------------- @@ -36,7 +37,7 @@ start(VHost) -> %% we can get here if a vhost is added and removed concurrently %% e.g. some integration tests do it {error, {no_such_vhost, VHost}} -> - rabbit_log:error("Failed to start a recovery terms manager for vhost ~ts: vhost no longer exists!", + ?LOG_ERROR("Failed to start a recovery terms manager for vhost ~ts: vhost no longer exists!", [VHost]), {error, {no_such_vhost, VHost}} end. @@ -52,7 +53,7 @@ stop(VHost) -> end; %% see start/1 {error, {no_such_vhost, VHost}} -> - rabbit_log:error("Failed to stop a recovery terms manager for vhost ~ts: vhost no longer exists!", + ?LOG_ERROR("Failed to stop a recovery terms manager for vhost ~ts: vhost no longer exists!", [VHost]), ok @@ -81,7 +82,7 @@ clear(VHost) -> ok %% see start/1 catch _:badarg -> - rabbit_log:error("Failed to clear recovery terms for vhost ~ts: table no longer exists!", + ?LOG_ERROR("Failed to clear recovery terms for vhost ~ts: table no longer exists!", [VHost]), ok end, @@ -138,7 +139,7 @@ open_table(VHost, RamFile, RetriesLeft) -> _ = file:delete(File), %% Wait before retrying DelayInMs = 1000, - rabbit_log:warning("Failed to open a recovery terms DETS file at ~tp. Will delete it and retry in ~tp ms (~tp retries left)", + ?LOG_WARNING("Failed to open a recovery terms DETS file at ~tp. Will delete it and retry in ~tp ms (~tp retries left)", [File, DelayInMs, RetriesLeft]), timer:sleep(DelayInMs), open_table(VHost, RamFile, RetriesLeft - 1) @@ -152,7 +153,7 @@ flush(VHost) -> dets:sync(VHost) %% see clear/1 catch _:badarg -> - rabbit_log:error("Failed to sync recovery terms table for vhost ~ts: the table no longer exists!", + ?LOG_ERROR("Failed to sync recovery terms table for vhost ~ts: the table no longer exists!", [VHost]), ok end. @@ -165,7 +166,7 @@ close_table(VHost) -> ok = dets:close(VHost) %% see clear/1 catch _:badarg -> - rabbit_log:error("Failed to close recovery terms table for vhost ~ts: the table no longer exists!", + ?LOG_ERROR("Failed to close recovery terms table for vhost ~ts: the table no longer exists!", [VHost]), ok end. diff --git a/deps/rabbit/src/rabbit_runtime_parameters.erl b/deps/rabbit/src/rabbit_runtime_parameters.erl index f919ad396900..7f22a599f57b 100644 --- a/deps/rabbit/src/rabbit_runtime_parameters.erl +++ b/deps/rabbit/src/rabbit_runtime_parameters.erl @@ -41,6 +41,7 @@ %% * rabbit_event -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([parse_set/5, set/5, set_any/5, clear/4, clear_any/4, list/0, list/1, list_component/1, list/2, list_formatted/1, list_formatted/3, @@ -104,7 +105,7 @@ parse_set_global(Name, String, ActingUser) -> set_global(Name, Term, ActingUser) -> NameAsAtom = rabbit_data_coercion:to_atom(Name), - rabbit_log:debug("Setting global parameter '~ts' to ~tp", [NameAsAtom, Term]), + ?LOG_DEBUG("Setting global parameter '~ts' to ~tp", [NameAsAtom, Term]), _ = rabbit_db_rtparams:set(NameAsAtom, Term), event_notify(parameter_set, none, global, [{name, NameAsAtom}, {value, Term}, @@ -125,7 +126,7 @@ set_any(VHost, Component, Name, Term, User) -> end. set_any0(VHost, Component, Name, Term, User) -> - rabbit_log:debug("Asked to set or update runtime parameter '~ts' in vhost '~ts' " + ?LOG_DEBUG("Asked to set or update runtime parameter '~ts' in vhost '~ts' " "for component '~ts', value: ~tp", [Name, VHost, Component, Term]), case lookup_component(Component) of @@ -168,7 +169,7 @@ is_within_limit(Component) -> false -> ErrorMsg = "Limit reached: component ~ts is limited to ~tp", ErrorArgs = [Component, Limit], - rabbit_log:error(ErrorMsg, ErrorArgs), + ?LOG_ERROR(ErrorMsg, ErrorArgs), {errors, [{"component ~ts is limited to ~tp", [Component, Limit]}]} end. diff --git a/deps/rabbit/src/rabbit_ssl.erl b/deps/rabbit/src/rabbit_ssl.erl index 6eafe2022951..f0e98b2dd195 100644 --- a/deps/rabbit/src/rabbit_ssl.erl +++ b/deps/rabbit/src/rabbit_ssl.erl @@ -8,6 +8,7 @@ -module(rabbit_ssl). -include_lib("public_key/include/public_key.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([peer_cert_issuer/1, peer_cert_subject/1, peer_cert_validity/1]). -export([peer_cert_subject_items/2, peer_cert_auth_name/1, peer_cert_auth_name/2]). @@ -161,7 +162,7 @@ peer_cert_auth_name({subject_alternative_name, Type, Index0}, Cert) -> %% lists:nth/2 is 1-based Index = Index0 + 1, OfType = peer_cert_subject_alternative_names(Cert, otp_san_type(Type)), - rabbit_log:debug("Peer certificate SANs of type ~ts: ~tp, index to use with lists:nth/2: ~b", [Type, OfType, Index]), + ?LOG_DEBUG("Peer certificate SANs of type ~ts: ~tp, index to use with lists:nth/2: ~b", [Type, OfType, Index]), case length(OfType) of 0 -> not_found; N when N < Index -> not_found; @@ -198,7 +199,7 @@ auth_config_sane() -> {ok, Opts} = application:get_env(rabbit, ssl_options), case proplists:get_value(verify, Opts) of verify_peer -> true; - V -> rabbit_log:warning("TLS peer verification (authentication) is " + V -> ?LOG_WARNING("TLS peer verification (authentication) is " "disabled, ssl_options.verify value used: ~tp. " "See https://www.rabbitmq.com/docs/ssl#peer-verification to learn more.", [V]), false diff --git a/deps/rabbit/src/rabbit_stream_coordinator.erl b/deps/rabbit/src/rabbit_stream_coordinator.erl index 9b25d8f23203..f2594ac538a2 100644 --- a/deps/rabbit/src/rabbit_stream_coordinator.erl +++ b/deps/rabbit/src/rabbit_stream_coordinator.erl @@ -83,6 +83,7 @@ -include("rabbit_stream_coordinator.hrl"). -include("amqqueue.hrl"). +-include_lib("kernel/include/logger.hrl"). -define(REPLICA_FRESHNESS_LIMIT_MS, 10 * 1000). %% 10s -define(V2_OR_MORE(Vsn), Vsn >= 2). @@ -174,7 +175,7 @@ restart_stream(QRes, Options) restart_stream(Q, Options) when ?is_amqqueue(Q) andalso ?amqqueue_is_stream(Q) -> - rabbit_log:info("restarting stream ~s in vhost ~s with options ~p", + ?LOG_INFO("restarting stream ~s in vhost ~s with options ~p", [maps:get(name, amqqueue:get_type_state(Q)), amqqueue:get_vhost(Q), Options]), #{name := StreamId} = amqqueue:get_type_state(Q), case process_command({restart_stream, StreamId, Options}) of @@ -217,7 +218,7 @@ add_replica(Q, Node) when ?is_amqqueue(Q) -> {error, {disallowed, out_of_sync_replica}}; false -> Name = rabbit_misc:rs(amqqueue:get_name(Q)), - rabbit_log:info("~ts : adding replica ~ts to ~ts Replication State: ~w", + ?LOG_INFO("~ts : adding replica ~ts to ~ts Replication State: ~w", [?MODULE, Node, Name, ReplState0]), StreamId = maps:get(name, amqqueue:get_type_state(Q)), case process_command({add_replica, StreamId, #{node => Node}}) of @@ -444,7 +445,7 @@ process_command([Server | Servers], Cmd) -> _ -> element(1, Cmd) end, - rabbit_log:warning("Coordinator timeout on server ~w when processing command ~W", + ?LOG_WARNING("Coordinator timeout on server ~w when processing command ~W", [element(2, Server), CmdLabel, 10]), process_command(Servers, Cmd); {error, noproc} -> @@ -516,17 +517,17 @@ start_coordinator_cluster() -> Versions = [V || {ok, V} <- erpc:multicall(Nodes, ?MODULE, version, [])], MinVersion = lists:min([version() | Versions]), - rabbit_log:debug("Starting stream coordinator on nodes: ~w, " + ?LOG_DEBUG("Starting stream coordinator on nodes: ~w, " "initial machine version ~b", [Nodes, MinVersion]), case ra:start_cluster(?RA_SYSTEM, [make_ra_conf(Node, Nodes, MinVersion) || Node <- Nodes]) of {ok, Started, _} -> - rabbit_log:debug("Started stream coordinator on ~w", [Started]), + ?LOG_DEBUG("Started stream coordinator on ~w", [Started]), Started; {error, cluster_not_formed} -> - rabbit_log:warning("Stream coordinator could not be started on nodes ~w", + ?LOG_WARNING("Stream coordinator could not be started on nodes ~w", [Nodes]), [] end. @@ -740,7 +741,7 @@ apply(Meta, {nodeup, Node} = Cmd, streams = Streams, single_active_consumer = Sac1}, ok, Effects2); apply(Meta, {machine_version, From, To}, State0) -> - rabbit_log:info("Stream coordinator machine version changes from ~tp to ~tp, " + ?LOG_INFO("Stream coordinator machine version changes from ~tp to ~tp, " ++ "applying incremental upgrade.", [From, To]), %% RA applies machine upgrades from any version to any version, e.g. 0 -> 2. %% We fill in the gaps here, applying all 1-to-1 machine upgrades. @@ -756,7 +757,7 @@ apply(Meta, {timeout, {sac, node_disconnected, #{connection_pid := Pid}}}, return(Meta, State0#?MODULE{single_active_consumer = SacState1}, ok, Effects); apply(Meta, UnkCmd, State) -> - rabbit_log:debug("~ts: unknown command ~W", + ?LOG_DEBUG("~ts: unknown command ~W", [?MODULE, UnkCmd, 10]), return(Meta, State, {error, unknown_command}, []). @@ -842,7 +843,7 @@ maybe_resize_coordinator_cluster(LeaderPid, SacNodes, MachineVersion) -> [New | _] -> %% any remaining members will be added %% next tick - rabbit_log:info("~ts: New rabbit node(s) detected, " + ?LOG_INFO("~ts: New rabbit node(s) detected, " "adding : ~w", [?MODULE, New]), add_member(Members, New) @@ -854,7 +855,7 @@ maybe_resize_coordinator_cluster(LeaderPid, SacNodes, MachineVersion) -> %% this ought to be rather rare as the stream %% coordinator member is now removed as part %% of the forget_cluster_node command - rabbit_log:info("~ts: Rabbit node(s) removed " + ?LOG_INFO("~ts: Rabbit node(s) removed " "from the cluster, " "deleting: ~w", [?MODULE, Old]), _ = remove_member(Leader, Members, Old), @@ -874,7 +875,7 @@ maybe_handle_stale_nodes(SacNodes, BrokerNodes, [] -> ok; Stale when length(BrokerNodes) > 0 -> - rabbit_log:debug("Stale nodes detected in stream SAC " + ?LOG_DEBUG("Stale nodes detected in stream SAC " "coordinator: ~w. Purging state.", [Stale]), ra:pipeline_command(LeaderPid, sac_make_purge_nodes(Stale)), @@ -903,14 +904,14 @@ add_member(Members, Node) -> {ok, _, _} -> ok; {error, Err} -> - rabbit_log:warning("~ts: Failed to add member, reason ~w" + ?LOG_WARNING("~ts: Failed to add member, reason ~w" "deleting started server on ~w", [?MODULE, Err, Node]), case ra:force_delete_server(?RA_SYSTEM, ServerId) of ok -> ok; Err -> - rabbit_log:warning("~ts: Failed to delete server " + ?LOG_WARNING("~ts: Failed to delete server " "on ~w, reason ~w", [?MODULE, Node, Err]), ok @@ -926,7 +927,7 @@ add_member(Members, Node) -> %% there is a server running but is not a member of the %% stream coordinator cluster %% In this case it needs to be deleted - rabbit_log:warning("~ts: server already running on ~w but not + ?LOG_WARNING("~ts: server already running on ~w but not part of cluster, " "deleting started server", [?MODULE, Node]), @@ -934,14 +935,14 @@ add_member(Members, Node) -> ok -> ok; Err -> - rabbit_log:warning("~ts: Failed to delete server " + ?LOG_WARNING("~ts: Failed to delete server " "on ~w, reason ~w", [?MODULE, Node, Err]), ok end end; Error -> - rabbit_log:warning("Stream coordinator server failed to start on node ~ts : ~W", + ?LOG_WARNING("Stream coordinator server failed to start on node ~ts : ~W", [Node, Error, 10]), ok end. @@ -983,7 +984,7 @@ handle_aux(leader, _, {down, Pid, _}, handle_aux(leader, _, {start_writer, StreamId, #{epoch := Epoch, node := Node} = Args, Conf}, Aux, RaAux) -> - rabbit_log:debug("~ts: running action: 'start_writer'" + ?LOG_DEBUG("~ts: running action: 'start_writer'" " for ~ts on node ~w in epoch ~b", [?MODULE, StreamId, Node, Epoch]), ActionFun = phase_start_writer(StreamId, Args, Conf), @@ -991,7 +992,7 @@ handle_aux(leader, _, {start_writer, StreamId, handle_aux(leader, _, {start_replica, StreamId, #{epoch := Epoch, node := Node} = Args, Conf}, Aux, RaAux) -> - rabbit_log:debug("~ts: running action: 'start_replica'" + ?LOG_DEBUG("~ts: running action: 'start_replica'" " for ~ts on node ~w in epoch ~b", [?MODULE, StreamId, Node, Epoch]), ActionFun = phase_start_replica(StreamId, Args, Conf), @@ -999,26 +1000,26 @@ handle_aux(leader, _, {start_replica, StreamId, handle_aux(leader, _, {stop, StreamId, #{node := Node, epoch := Epoch} = Args, Conf}, Aux, RaAux) -> - rabbit_log:debug("~ts: running action: 'stop'" + ?LOG_DEBUG("~ts: running action: 'stop'" " for ~ts on node ~w in epoch ~b", [?MODULE, StreamId, Node, Epoch]), ActionFun = phase_stop_member(StreamId, Args, Conf), run_action(stopping, StreamId, Args, ActionFun, Aux, RaAux); handle_aux(leader, _, {update_mnesia, StreamId, Args, Conf}, #aux{actions = _Monitors} = Aux, RaAux) -> - rabbit_log:debug("~ts: running action: 'update_mnesia'" + ?LOG_DEBUG("~ts: running action: 'update_mnesia'" " for ~ts", [?MODULE, StreamId]), ActionFun = phase_update_mnesia(StreamId, Args, Conf), run_action(updating_mnesia, StreamId, Args, ActionFun, Aux, RaAux); handle_aux(leader, _, {update_retention, StreamId, Args, _Conf}, #aux{actions = _Monitors} = Aux, RaAux) -> - rabbit_log:debug("~ts: running action: 'update_retention'" + ?LOG_DEBUG("~ts: running action: 'update_retention'" " for ~ts", [?MODULE, StreamId]), ActionFun = phase_update_retention(StreamId, Args), run_action(update_retention, StreamId, Args, ActionFun, Aux, RaAux); handle_aux(leader, _, {delete_member, StreamId, #{node := Node} = Args, Conf}, #aux{actions = _Monitors} = Aux, RaAux) -> - rabbit_log:debug("~ts: running action: 'delete_member'" + ?LOG_DEBUG("~ts: running action: 'delete_member'" " for ~ts ~ts", [?MODULE, StreamId, Node]), ActionFun = phase_delete_member(StreamId, Args, Conf), run_action(delete_member, StreamId, Args, ActionFun, Aux, RaAux); @@ -1030,7 +1031,7 @@ handle_aux(leader, _, fail_active_actions, Exclude = maps:from_list([{S, ok} || {P, {S, _, _}} <- maps_to_list(Actions), is_process_alive(P)]), - rabbit_log:debug("~ts: failing actions: ~w", [?MODULE, Exclude]), + ?LOG_DEBUG("~ts: failing actions: ~w", [?MODULE, Exclude]), #?MODULE{streams = Streams} = ra_aux:machine_state(RaAux), fail_active_actions(Streams, Exclude), {no_reply, Aux, RaAux, []}; @@ -1043,7 +1044,7 @@ handle_aux(leader, _, {down, Pid, Reason}, %% An action has failed - report back to the state machine case maps:get(Pid, Monitors0, undefined) of {StreamId, Action, #{node := Node, epoch := Epoch} = Args} -> - rabbit_log:warning("~ts: error while executing action ~w for stream queue ~ts, " + ?LOG_WARNING("~ts: error while executing action ~w for stream queue ~ts, " " node ~ts, epoch ~b Err: ~w", [?MODULE, Action, StreamId, Node, Epoch, Reason]), Monitors = maps:remove(Pid, Monitors0), @@ -1110,7 +1111,7 @@ phase_start_replica(StreamId, #{epoch := Epoch, fun() -> try osiris_replica:start(Node, Conf0) of {ok, Pid} -> - rabbit_log:info("~ts: ~ts: replica started on ~ts in ~b pid ~w", + ?LOG_INFO("~ts: ~ts: replica started on ~ts in ~b pid ~w", [?MODULE, StreamId, Node, Epoch, Pid]), send_self_command({member_started, StreamId, Args#{pid => Pid}}); @@ -1126,12 +1127,12 @@ phase_start_replica(StreamId, #{epoch := Epoch, send_self_command({member_started, StreamId, Args#{pid => Pid}}); {error, Reason} -> - rabbit_log:warning("~ts: Error while starting replica for ~ts on node ~ts in ~b : ~W", + ?LOG_WARNING("~ts: Error while starting replica for ~ts on node ~ts in ~b : ~W", [?MODULE, maps:get(name, Conf0), Node, Epoch, Reason, 10]), maybe_sleep(Reason), send_action_failed(StreamId, starting, Args) catch _:Error -> - rabbit_log:warning("~ts: Error while starting replica for ~ts on node ~ts in ~b : ~W", + ?LOG_WARNING("~ts: Error while starting replica for ~ts on node ~ts in ~b : ~W", [?MODULE, maps:get(name, Conf0), Node, Epoch, Error, 10]), maybe_sleep(Error), send_action_failed(StreamId, starting, Args) @@ -1152,13 +1153,13 @@ phase_delete_member(StreamId, #{node := Node} = Arg, Conf) -> true -> try osiris:delete_member(Node, Conf) of ok -> - rabbit_log:info("~ts: Member deleted for ~ts : on node ~ts", + ?LOG_INFO("~ts: Member deleted for ~ts : on node ~ts", [?MODULE, StreamId, Node]), send_self_command({member_deleted, StreamId, Arg}); _ -> send_action_failed(StreamId, deleting, Arg) catch _:E -> - rabbit_log:warning("~ts: Error while deleting member for ~ts : on node ~ts ~W", + ?LOG_WARNING("~ts: Error while deleting member for ~ts : on node ~ts ~W", [?MODULE, StreamId, Node, E, 10]), maybe_sleep(E), send_action_failed(StreamId, deleting, Arg) @@ -1166,7 +1167,7 @@ phase_delete_member(StreamId, #{node := Node} = Arg, Conf) -> false -> %% node is no longer a cluster member, we return success to avoid %% trying to delete the member indefinitely - rabbit_log:info("~ts: Member deleted/forgotten for ~ts : node ~ts is no longer a cluster member", + ?LOG_INFO("~ts: Member deleted/forgotten for ~ts : node ~ts is no longer a cluster member", [?MODULE, StreamId, Node]), send_self_command({member_deleted, StreamId, Arg}) end @@ -1180,22 +1181,22 @@ phase_stop_member(StreamId, #{node := Node, epoch := Epoch} = Arg0, Conf) -> try get_replica_tail(Node, Conf) of {ok, Tail} -> Arg = Arg0#{tail => Tail}, - rabbit_log:debug("~ts: ~ts: member stopped on ~ts in ~b Tail ~w", + ?LOG_DEBUG("~ts: ~ts: member stopped on ~ts in ~b Tail ~w", [?MODULE, StreamId, Node, Epoch, Tail]), send_self_command({member_stopped, StreamId, Arg}); Err -> - rabbit_log:warning("~ts: failed to get tail of member ~ts on ~ts in ~b Error: ~w", + ?LOG_WARNING("~ts: failed to get tail of member ~ts on ~ts in ~b Error: ~w", [?MODULE, StreamId, Node, Epoch, Err]), maybe_sleep(Err), send_action_failed(StreamId, stopping, Arg0) catch _:Err -> - rabbit_log:warning("~ts: failed to get tail of member ~ts on ~ts in ~b Error: ~w", + ?LOG_WARNING("~ts: failed to get tail of member ~ts on ~ts in ~b Error: ~w", [?MODULE, StreamId, Node, Epoch, Err]), maybe_sleep(Err), send_action_failed(StreamId, stopping, Arg0) end catch _:Err -> - rabbit_log:warning("~ts: failed to stop member ~ts ~w Error: ~w", + ?LOG_WARNING("~ts: failed to stop member ~ts ~w Error: ~w", [?MODULE, StreamId, Node, Err]), maybe_sleep(Err), send_action_failed(StreamId, stopping, Arg0) @@ -1207,17 +1208,17 @@ phase_start_writer(StreamId, #{epoch := Epoch, node := Node} = Args0, Conf) -> try osiris:start_writer(Conf) of {ok, Pid} -> Args = Args0#{epoch => Epoch, pid => Pid}, - rabbit_log:info("~ts: started writer ~ts on ~w in ~b", + ?LOG_INFO("~ts: started writer ~ts on ~w in ~b", [?MODULE, StreamId, Node, Epoch]), send_self_command({member_started, StreamId, Args}); Err -> %% no sleep for writer failures as we want to trigger a new %% election asap - rabbit_log:warning("~ts: failed to start writer ~ts on ~ts in ~b Error: ~w", + ?LOG_WARNING("~ts: failed to start writer ~ts on ~ts in ~b Error: ~w", [?MODULE, StreamId, Node, Epoch, Err]), send_action_failed(StreamId, starting, Args0) catch _:Err -> - rabbit_log:warning("~ts: failed to start writer ~ts on ~ts in ~b Error: ~w", + ?LOG_WARNING("~ts: failed to start writer ~ts on ~ts in ~b Error: ~w", [?MODULE, StreamId, Node, Epoch, Err]), send_action_failed(StreamId, starting, Args0) end @@ -1230,12 +1231,12 @@ phase_update_retention(StreamId, #{pid := Pid, ok -> send_self_command({retention_updated, StreamId, Args}); {error, Reason} = Err -> - rabbit_log:warning("~ts: failed to update retention for ~ts ~w Reason: ~w", + ?LOG_WARNING("~ts: failed to update retention for ~ts ~w Reason: ~w", [?MODULE, StreamId, node(Pid), Reason]), maybe_sleep(Err), send_action_failed(StreamId, update_retention, Args) catch _:Err -> - rabbit_log:warning("~ts: failed to update retention for ~ts ~w Error: ~w", + ?LOG_WARNING("~ts: failed to update retention for ~ts ~w Error: ~w", [?MODULE, StreamId, node(Pid), Err]), maybe_sleep(Err), send_action_failed(StreamId, update_retention, Args) @@ -1281,7 +1282,7 @@ is_quorum(NumReplicas, NumAlive) -> phase_update_mnesia(StreamId, Args, #{reference := QName, leader_pid := LeaderPid} = Conf) -> fun() -> - rabbit_log:debug("~ts: running mnesia update for ~ts: ~W", + ?LOG_DEBUG("~ts: running mnesia update for ~ts: ~W", [?MODULE, StreamId, Conf, 10]), Fun = fun (Q) -> case amqqueue:get_type_state(Q) of @@ -1293,7 +1294,7 @@ phase_update_mnesia(StreamId, Args, #{reference := QName, Ts -> S = maps:get(name, Ts, undefined), %% TODO log as side-effect - rabbit_log:debug("~ts: refusing mnesia update for stale stream id ~s, current ~s", + ?LOG_DEBUG("~ts: refusing mnesia update for stale stream id ~s, current ~s", [?MODULE, StreamId, S]), %% if the stream id isn't a match this is a stale %% update from a previous stream incarnation for the @@ -1303,7 +1304,7 @@ phase_update_mnesia(StreamId, Args, #{reference := QName, end, try rabbit_amqqueue:update(QName, Fun) of not_found -> - rabbit_log:debug("~ts: resource for stream id ~ts not found, " + ?LOG_DEBUG("~ts: resource for stream id ~ts not found, " "recovering from rabbit_durable_queue", [?MODULE, StreamId]), %% This can happen during recovery @@ -1316,7 +1317,7 @@ phase_update_mnesia(StreamId, Args, #{reference := QName, {ok, Q} -> case amqqueue:get_type_state(Q) of #{name := S} when S == StreamId -> - rabbit_log:debug("~ts: initializing queue record for stream id ~ts", + ?LOG_DEBUG("~ts: initializing queue record for stream id ~ts", [?MODULE, StreamId]), ok = rabbit_amqqueue:ensure_rabbit_queue_record_is_initialized(Fun(Q)), ok; @@ -1328,7 +1329,7 @@ phase_update_mnesia(StreamId, Args, #{reference := QName, _ -> send_self_command({mnesia_updated, StreamId, Args}) catch _:E -> - rabbit_log:debug("~ts: failed to update mnesia for ~ts: ~W", + ?LOG_DEBUG("~ts: failed to update mnesia for ~ts: ~W", [?MODULE, StreamId, E, 10]), send_action_failed(StreamId, updating_mnesia, Args) end @@ -1364,7 +1365,7 @@ filter_command(_Meta, {delete_replica, _, #{node := Node}}, #stream{id = StreamI end, Members0), case maps:size(Members) =< 1 of true -> - rabbit_log:warning( + ?LOG_WARNING( "~ts failed to delete replica on node ~ts for stream ~ts: refusing to delete the only replica", [?MODULE, Node, StreamId]), {error, last_stream_member}; @@ -1379,7 +1380,7 @@ update_stream(Meta, Cmd, Stream) -> update_stream0(Meta, Cmd, Stream) catch _:E:Stacktrace -> - rabbit_log:warning( + ?LOG_WARNING( "~ts failed to update stream:~n~W~n~W", [?MODULE, E, 10, Stacktrace, 10]), Stream @@ -1495,7 +1496,7 @@ update_stream0(#{system_time := _Ts}, Member -> %% do we just ignore any members started events from unexpected %% epochs? - rabbit_log:warning("~ts: member started unexpected ~w ~w", + ?LOG_WARNING("~ts: member started unexpected ~w ~w", [?MODULE, Args, Member]), Stream0 end; @@ -2056,7 +2057,7 @@ fail_active_actions(Streams, Exclude) -> end, Members), case Mnesia of {updating, E} -> - rabbit_log:debug("~ts: failing stale action to trigger retry. " + ?LOG_DEBUG("~ts: failing stale action to trigger retry. " "Stream ID: ~ts, node: ~w, action: ~w", [?MODULE, Id, node(), updating_mnesia]), send_self_command({action_failed, Id, @@ -2076,7 +2077,7 @@ fail_action(_StreamId, _, #member{current = undefined}) -> ok; fail_action(StreamId, Node, #member{role = {_, E}, current = {Action, Idx}}) -> - rabbit_log:debug("~ts: failing stale action to trigger retry. " + ?LOG_DEBUG("~ts: failing stale action to trigger retry. " "Stream ID: ~ts, node: ~w, action: ~w", [?MODULE, StreamId, node(), Action]), %% if we have an action send failure message @@ -2241,7 +2242,7 @@ update_target(Member, Target) -> machine_version(1, 2, State = #?MODULE{streams = Streams0, monitors = Monitors0}) -> - rabbit_log:info("Stream coordinator machine version changes from 1 to 2, updating state."), + ?LOG_INFO("Stream coordinator machine version changes from 1 to 2, updating state."), %% conversion from old state to new state %% additional operation: the stream listeners are never collected in the previous version %% so we'll emit monitors for all listener PIDs @@ -2273,13 +2274,13 @@ machine_version(1, 2, State = #?MODULE{streams = Streams0, monitors = Monitors2, listeners = undefined}, Effects}; machine_version(2, 3, State) -> - rabbit_log:info("Stream coordinator machine version changes from 2 to 3, " + ?LOG_INFO("Stream coordinator machine version changes from 2 to 3, " "updating state."), SacState = rabbit_stream_sac_coordinator_v4:init_state(), {State#?MODULE{single_active_consumer = SacState}, []}; machine_version(3, 4, #?MODULE{streams = Streams0} = State) -> - rabbit_log:info("Stream coordinator machine version changes from 3 to 4, updating state."), + ?LOG_INFO("Stream coordinator machine version changes from 3 to 4, updating state."), %% the "preferred" field takes the place of the "node" field in this version %% initializing the "preferred" field to false Streams = maps:map( @@ -2291,12 +2292,12 @@ machine_version(3, 4, #?MODULE{streams = Streams0} = State) -> end, Streams0), {State#?MODULE{streams = Streams}, []}; machine_version(4 = From, 5, #?MODULE{single_active_consumer = Sac0} = State) -> - rabbit_log:info("Stream coordinator machine version changes from 4 to 5, updating state."), + ?LOG_INFO("Stream coordinator machine version changes from 4 to 5, updating state."), SacExport = rabbit_stream_sac_coordinator_v4:state_to_map(Sac0), Sac1 = rabbit_stream_sac_coordinator:import_state(From, SacExport), {State#?MODULE{single_active_consumer = Sac1}, []}; machine_version(From, To, State) -> - rabbit_log:info("Stream coordinator machine version changes from ~tp to ~tp, no state changes required.", + ?LOG_INFO("Stream coordinator machine version changes from ~tp to ~tp, no state changes required.", [From, To]), {State, []}. diff --git a/deps/rabbit/src/rabbit_stream_queue.erl b/deps/rabbit/src/rabbit_stream_queue.erl index 3a14d63c00ee..f39c4a15c41e 100644 --- a/deps/rabbit/src/rabbit_stream_queue.erl +++ b/deps/rabbit/src/rabbit_stream_queue.erl @@ -70,6 +70,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include("amqqueue.hrl"). +-include_lib("kernel/include/logger.hrl"). -define(INFO_KEYS, [name, durable, auto_delete, arguments, leader, members, online, state, messages, messages_ready, messages_unacknowledged, committed_offset, @@ -332,7 +333,7 @@ consume(Q, Spec, #stream_client{} = QState0) args := Args, ok_msg := OkMsg, acting_user := ActingUser} = Spec, - rabbit_log:debug("~s:~s Local pid resolved ~0p", + ?LOG_DEBUG("~s:~s Local pid resolved ~0p", [?MODULE, ?FUNCTION_NAME, LocalPid]), case parse_offset_arg( rabbit_misc:table_lookup(Args, <<"x-stream-offset">>)) of @@ -643,17 +644,17 @@ handle_event(_QName, {stream_local_member_change, Pid}, handle_event(_QName, {stream_local_member_change, Pid}, #stream_client{name = QName, readers = Readers0} = State) -> - rabbit_log:debug("Local member change event for ~tp", [QName]), + ?LOG_DEBUG("Local member change event for ~tp", [QName]), Readers1 = maps:fold(fun(T, #stream{log = Log0, reader_options = Options} = S0, Acc) -> Offset = osiris_log:next_offset(Log0), osiris_log:close(Log0), CounterSpec = {{?MODULE, QName, self()}, []}, - rabbit_log:debug("Re-creating Osiris reader for consumer ~tp at offset ~tp " + ?LOG_DEBUG("Re-creating Osiris reader for consumer ~tp at offset ~tp " " with options ~tp", [T, Offset, Options]), {ok, Log1} = osiris:init_reader(Pid, Offset, CounterSpec, Options), NextOffset = osiris_log:next_offset(Log1) - 1, - rabbit_log:debug("Registering offset listener at offset ~tp", [NextOffset]), + ?LOG_DEBUG("Registering offset listener at offset ~tp", [NextOffset]), osiris:register_offset_listener(Pid, NextOffset), S1 = S0#stream{listening_offset = NextOffset, log = Log1}, @@ -1000,7 +1001,7 @@ init(Q) when ?is_amqqueue(Q) -> {ok, stream_not_found, _} -> {error, stream_not_found}; {error, coordinator_unavailable} = E -> - rabbit_log:warning("Failed to start stream client ~tp: coordinator unavailable", + ?LOG_WARNING("Failed to start stream client ~tp: coordinator unavailable", [rabbit_misc:rs(QName)]), E end. @@ -1019,7 +1020,7 @@ update(Q, State) update_leader_pid(Pid, #stream_client{leader = Pid} = State) -> State; update_leader_pid(Pid, #stream_client{} = State) -> - rabbit_log:debug("stream client: new leader detected ~w", [Pid]), + ?LOG_DEBUG("stream client: new leader detected ~w", [Pid]), resend_all(State#stream_client{leader = Pid}). state_info(_) -> @@ -1080,11 +1081,11 @@ delete_replica(VHost, Name, Node) -> end. delete_all_replicas(Node) -> - rabbit_log:info("Asked to remove all stream replicas from node ~ts", [Node]), + ?LOG_INFO("Asked to remove all stream replicas from node ~ts", [Node]), Streams = rabbit_amqqueue:list_stream_queues_on(Node), lists:map(fun(Q) -> QName = amqqueue:get_name(Q), - rabbit_log:info("~ts: removing replica on node ~w", + ?LOG_INFO("~ts: removing replica on node ~w", [rabbit_misc:rs(QName), Node]), #{name := StreamId} = amqqueue:get_type_state(Q), {ok, Reply, _} = rabbit_stream_coordinator:delete_replica(StreamId, Node), @@ -1092,7 +1093,7 @@ delete_all_replicas(Node) -> ok -> {QName, ok}; Err -> - rabbit_log:warning("~ts: failed to remove replica on node ~w, error: ~w", + ?LOG_WARNING("~ts: failed to remove replica on node ~w, error: ~w", [rabbit_misc:rs(QName), Node, Err]), {QName, {error, Err}} end @@ -1286,7 +1287,7 @@ chunk_iterator(#stream{credit = Credit, end, {end_of_stream, Str}; {error, Err} -> - rabbit_log:info("stream client: failed to create chunk iterator ~p", [Err]), + ?LOG_INFO("stream client: failed to create chunk iterator ~p", [Err]), exit(Err) end. @@ -1365,7 +1366,7 @@ resend_all(#stream_client{leader = LeaderPid, case Msgs of [] -> ok; [{Seq, _} | _] -> - rabbit_log:debug("stream client: resending from seq ~w num ~b", + ?LOG_DEBUG("stream client: resending from seq ~w num ~b", [Seq, maps:size(Corrs)]) end, [begin @@ -1444,7 +1445,7 @@ revive() -> -spec transfer_leadership_of_stream_coordinator([node()]) -> ok. transfer_leadership_of_stream_coordinator([]) -> - rabbit_log:warning("Skipping leadership transfer of stream coordinator: no candidate " + ?LOG_WARNING("Skipping leadership transfer of stream coordinator: no candidate " "(online, not under maintenance) nodes to transfer to!"); transfer_leadership_of_stream_coordinator(TransferCandidates) -> % try to transfer to the node with the lowest uptime; the assumption is that @@ -1456,9 +1457,9 @@ transfer_leadership_of_stream_coordinator(TransferCandidates) -> BestCandidate = element(1, hd(lists:keysort(2, Candidates))), case rabbit_stream_coordinator:transfer_leadership([BestCandidate]) of {ok, Node} -> - rabbit_log:info("Leadership transfer for stream coordinator completed. The new leader is ~p", [Node]); + ?LOG_INFO("Leadership transfer for stream coordinator completed. The new leader is ~p", [Node]); Error -> - rabbit_log:warning("Skipping leadership transfer of stream coordinator: ~p", [Error]) + ?LOG_WARNING("Skipping leadership transfer of stream coordinator: ~p", [Error]) end. queue_vm_stats_sups() -> diff --git a/deps/rabbit/src/rabbit_stream_sac_coordinator.erl b/deps/rabbit/src/rabbit_stream_sac_coordinator.erl index 68883275287a..ec80ec3f4363 100644 --- a/deps/rabbit/src/rabbit_stream_sac_coordinator.erl +++ b/deps/rabbit/src/rabbit_stream_sac_coordinator.erl @@ -17,6 +17,7 @@ -module(rabbit_stream_sac_coordinator). -include("rabbit_stream_sac_coordinator.hrl"). +-include_lib("kernel/include/logger.hrl"). -opaque command() :: #command_register_consumer{} | #command_unregister_consumer{} | @@ -148,7 +149,7 @@ process_command(Cmd) -> {ok, Res, _} -> Res; {error, _} = Err -> - rabbit_log:warning("SAC coordinator command ~tp returned error ~tp", + ?LOG_WARNING("SAC coordinator command ~tp returned error ~tp", [Cmd, Err]), Err end. @@ -286,7 +287,7 @@ apply(#command_activate_consumer{vhost = VH, stream = S, consumer_name = Name}, {G, Eff} = case lookup_group(VH, S, Name, StreamGroups0) of undefined -> - rabbit_log:warning("Trying to activate consumer in group ~tp, but " + ?LOG_WARNING("Trying to activate consumer in group ~tp, but " "the group does not longer exist", [{VH, S, Name}]), {undefined, []}; @@ -348,7 +349,7 @@ apply(#command_purge_nodes{nodes = Nodes}, State0) -> apply(#command_update_conf{conf = NewConf}, State) -> {State#?MODULE{conf = NewConf}, ok, []}; apply(UnkCmd, State) -> - rabbit_log:debug("~ts: unknown SAC command ~W", [?MODULE, UnkCmd, 10]), + ?LOG_DEBUG("~ts: unknown SAC command ~W", [?MODULE, UnkCmd, 10]), {State, {error, unknown_command}, []}. purge_node(Node, #?MODULE{groups = Groups0} = State0) -> diff --git a/deps/rabbit/src/rabbit_stream_sac_coordinator_v4.erl b/deps/rabbit/src/rabbit_stream_sac_coordinator_v4.erl index 0244e4323dc7..29f1f1ee8e91 100644 --- a/deps/rabbit/src/rabbit_stream_sac_coordinator_v4.erl +++ b/deps/rabbit/src/rabbit_stream_sac_coordinator_v4.erl @@ -17,6 +17,7 @@ -module(rabbit_stream_sac_coordinator_v4). -include("rabbit_stream_sac_coordinator_v4.hrl"). +-include_lib("kernel/include/logger.hrl"). -opaque command() :: #command_register_consumer{} | #command_unregister_consumer{} | @@ -124,7 +125,7 @@ process_command(Cmd) -> {ok, Res, _} -> Res; {error, _} = Err -> - rabbit_log:warning("SAC coordinator command ~tp returned error ~tp", + ?LOG_WARNING("SAC coordinator command ~tp returned error ~tp", [Cmd, Err]), Err end. @@ -251,7 +252,7 @@ apply(#command_activate_consumer{vhost = VirtualHost, {G, Eff} = case lookup_group(VirtualHost, Stream, ConsumerName, StreamGroups0) of undefined -> - rabbit_log:warning("Trying to activate consumer in group ~tp, but " + ?LOG_WARNING("Trying to activate consumer in group ~tp, but " "the group does not longer exist", [{VirtualHost, Stream, ConsumerName}]), {undefined, []}; diff --git a/deps/rabbit/src/rabbit_sysmon_handler.erl b/deps/rabbit/src/rabbit_sysmon_handler.erl index 1d4940641a08..96d063d021c4 100644 --- a/deps/rabbit/src/rabbit_sysmon_handler.erl +++ b/deps/rabbit/src/rabbit_sysmon_handler.erl @@ -23,6 +23,9 @@ -module(rabbit_sysmon_handler). +-include_lib("kernel/include/logger.hrl"). + + -behaviour(gen_event). %% API @@ -89,16 +92,16 @@ handle_event({monitor, PidOrPort, Type, Info}, State=#state{timer_ref=TimerRef}) %% Reset the inactivity timeout NewTimerRef = reset_timer(TimerRef), {Fmt, Args} = format_pretty_proc_or_port_info(PidOrPort), - rabbit_log:warning("~tp ~w ~w " ++ Fmt ++ " ~w", [?MODULE, Type, PidOrPort] ++ Args ++ [Info]), + ?LOG_WARNING("~tp ~w ~w " ++ Fmt ++ " ~w", [?MODULE, Type, PidOrPort] ++ Args ++ [Info]), {ok, State#state{timer_ref=NewTimerRef}}; handle_event({suppressed, Type, Info}, State=#state{timer_ref=TimerRef}) -> %% Reset the inactivity timeout NewTimerRef = reset_timer(TimerRef), - rabbit_log:debug("~tp encountered a suppressed event of type ~w: ~w", [?MODULE, Type, Info]), + ?LOG_DEBUG("~tp encountered a suppressed event of type ~w: ~w", [?MODULE, Type, Info]), {ok, State#state{timer_ref=NewTimerRef}}; handle_event(Event, State=#state{timer_ref=TimerRef}) -> NewTimerRef = reset_timer(TimerRef), - rabbit_log:warning("~tp unhandled event: ~tp", [?MODULE, Event]), + ?LOG_WARNING("~tp unhandled event: ~tp", [?MODULE, Event]), {ok, State#state{timer_ref=NewTimerRef}}. %%-------------------------------------------------------------------- @@ -136,7 +139,7 @@ handle_info(inactivity_timeout, State) -> %% so hibernate to free up resources. {ok, State, hibernate}; handle_info(Info, State) -> - rabbit_log:info("handle_info got ~tp", [Info]), + ?LOG_INFO("handle_info got ~tp", [Info]), {ok, State}. %%-------------------------------------------------------------------- diff --git a/deps/rabbit/src/rabbit_table.erl b/deps/rabbit/src/rabbit_table.erl index 9ed9073a2483..d0871f7c210b 100644 --- a/deps/rabbit/src/rabbit_table.erl +++ b/deps/rabbit/src/rabbit_table.erl @@ -20,6 +20,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -ifdef(TEST). -export([pre_khepri_definitions/0]). @@ -46,7 +47,7 @@ create() -> create(TableName, TableDefinition) -> TableDefinition1 = proplists:delete(match, TableDefinition), - rabbit_log:debug("Will create a schema database table '~ts'", [TableName]), + ?LOG_DEBUG("Will create a schema database table '~ts'", [TableName]), case mnesia:create_table(TableName, TableDefinition1) of {atomic, ok} -> ok; {aborted,{already_exists, TableName}} -> ok; @@ -78,7 +79,7 @@ ensure_secondary_index(Table, Field) -> -spec ensure_table_copy(mnesia_table(), node(), mnesia_storage_type()) -> ok | {error, any()}. ensure_table_copy(TableName, Node, StorageType) -> - rabbit_log:debug("Will add a local schema database copy for table '~ts'", [TableName]), + ?LOG_DEBUG("Will add a local schema database copy for table '~ts'", [TableName]), case mnesia:add_table_copy(TableName, Node, StorageType) of {atomic, ok} -> ok; {aborted,{already_exists, TableName}} -> ok; @@ -140,7 +141,7 @@ wait1(TableNames, Timeout, Retries, Silent) -> true -> ok; false -> - rabbit_log:info("Waiting for Mnesia tables for ~tp ms, ~tp retries left", + ?LOG_INFO("Waiting for Mnesia tables for ~tp ms, ~tp retries left", [Timeout, Retries - 1]) end, Result = case mnesia:wait_for_tables(TableNames, Timeout) of @@ -159,7 +160,7 @@ wait1(TableNames, Timeout, Retries, Silent) -> true -> ok; false -> - rabbit_log:info("Successfully synced tables from a peer"), + ?LOG_INFO("Successfully synced tables from a peer"), ok end; {1, {error, _} = Error} -> @@ -169,7 +170,7 @@ wait1(TableNames, Timeout, Retries, Silent) -> true -> ok; false -> - rabbit_log:warning("Error while waiting for Mnesia tables: ~tp", [Error]) + ?LOG_WARNING("Error while waiting for Mnesia tables: ~tp", [Error]) end, wait1(TableNames, Timeout, Retries - 1, Silent) end. diff --git a/deps/rabbit/src/rabbit_trace.erl b/deps/rabbit/src/rabbit_trace.erl index dccc18bef43d..9400cf7dc0c3 100644 --- a/deps/rabbit/src/rabbit_trace.erl +++ b/deps/rabbit/src/rabbit_trace.erl @@ -12,6 +12,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include_lib("rabbit_common/include/rabbit_framing.hrl"). +-include_lib("kernel/include/logger.hrl"). -define(TRACE_VHOSTS, trace_vhosts). -define(XNAME, <<"amq.rabbitmq.trace">>). @@ -103,10 +104,10 @@ start(VHost) when is_binary(VHost) -> case enabled(VHost) of true -> - rabbit_log:info("Tracing is already enabled for vhost '~ts'", [VHost]), + ?LOG_INFO("Tracing is already enabled for vhost '~ts'", [VHost]), ok; false -> - rabbit_log:info("Enabling tracing for vhost '~ts'", [VHost]), + ?LOG_INFO("Enabling tracing for vhost '~ts'", [VHost]), update_config(fun(VHosts) -> lists:usort([VHost | VHosts]) end) end. @@ -115,10 +116,10 @@ stop(VHost) when is_binary(VHost) -> case enabled(VHost) of true -> - rabbit_log:info("Disabling tracing for vhost '~ts'", [VHost]), + ?LOG_INFO("Disabling tracing for vhost '~ts'", [VHost]), update_config(fun(VHosts) -> VHosts -- [VHost] end); false -> - rabbit_log:info("Tracing is already disabled for vhost '~ts'", [VHost]), + ?LOG_INFO("Tracing is already disabled for vhost '~ts'", [VHost]), ok end. @@ -128,13 +129,13 @@ update_config(Fun) -> application:set_env(rabbit, ?TRACE_VHOSTS, VHosts), Sessions = rabbit_amqp_session:list_local(), NonAmqpPids = rabbit_networking:local_non_amqp_connections(), - rabbit_log:debug("Refreshing state of channels, ~b sessions and ~b non " + ?LOG_DEBUG("Refreshing state of channels, ~b sessions and ~b non " "AMQP 0.9.1 connections after virtual host tracing changes...", [length(Sessions), length(NonAmqpPids)]), Pids = Sessions ++ NonAmqpPids, lists:foreach(fun(Pid) -> gen_server:cast(Pid, refresh_config) end, Pids), {Time, ok} = timer:tc(fun rabbit_channel:refresh_config_local/0), - rabbit_log:debug("Refreshed channel states in ~fs", [Time / 1_000_000]), + ?LOG_DEBUG("Refreshed channel states in ~fs", [Time / 1_000_000]), ok. vhosts_with_tracing_enabled() -> diff --git a/deps/rabbit/src/rabbit_tracking.erl b/deps/rabbit/src/rabbit_tracking.erl index 7e966dde6bdc..1fed6b07e24c 100644 --- a/deps/rabbit/src/rabbit_tracking.erl +++ b/deps/rabbit/src/rabbit_tracking.erl @@ -7,6 +7,9 @@ -module(rabbit_tracking). +-include_lib("kernel/include/logger.hrl"). + + %% Common behaviour and processing functions for tracking components %% %% See in use: @@ -45,12 +48,12 @@ count_on_all_nodes(Mod, Fun, Args, ContextMsg) -> sum_rpc_multicall_result([{ok, Int}|ResL], [_N|Nodes], ContextMsg, Acc) when is_integer(Int) -> sum_rpc_multicall_result(ResL, Nodes, ContextMsg, Acc + Int); sum_rpc_multicall_result([{ok, BadValue}|ResL], [BadNode|Nodes], ContextMsg, Acc) -> - rabbit_log:error( + ?LOG_ERROR( "Failed to fetch number of ~ts on node ~tp:~n not an integer ~tp", [ContextMsg, BadNode, BadValue]), sum_rpc_multicall_result(ResL, Nodes, ContextMsg, Acc); sum_rpc_multicall_result([{Class, Reason}|ResL], [BadNode|Nodes], ContextMsg, Acc) -> - rabbit_log:error( + ?LOG_ERROR( "Failed to fetch number of ~ts on node ~tp:~n~tp:~tp", [ContextMsg, BadNode, Class, Reason]), sum_rpc_multicall_result(ResL, Nodes, ContextMsg, Acc); diff --git a/deps/rabbit/src/rabbit_upgrade_preparation.erl b/deps/rabbit/src/rabbit_upgrade_preparation.erl index a6df3572d8de..c04fa25bad33 100644 --- a/deps/rabbit/src/rabbit_upgrade_preparation.erl +++ b/deps/rabbit/src/rabbit_upgrade_preparation.erl @@ -7,6 +7,9 @@ -module(rabbit_upgrade_preparation). +-include_lib("kernel/include/logger.hrl"). + + -export([await_online_quorum_plus_one/1, list_with_minimum_quorum_for_cli/0]). @@ -64,12 +67,12 @@ do_await_safe_online_quorum(IterationsLeft) -> 0 -> case length(EndangeredQueues) of 0 -> ok; - N -> rabbit_log:info("Waiting for ~p queues and streams to have quorum+1 replicas online. " + N -> ?LOG_INFO("Waiting for ~p queues and streams to have quorum+1 replicas online. " "You can list them with `rabbitmq-diagnostics check_if_node_is_quorum_critical`", [N]) end, case endangered_critical_components() of [] -> ok; - _ -> rabbit_log:info("Waiting for the following critical components to have quorum+1 replicas online: ~p.", + _ -> ?LOG_INFO("Waiting for the following critical components to have quorum+1 replicas online: ~p.", [endangered_critical_components()]) end; _ -> diff --git a/deps/rabbit/src/rabbit_variable_queue.erl b/deps/rabbit/src/rabbit_variable_queue.erl index 2ffca81a3d1c..ed951bca34e9 100644 --- a/deps/rabbit/src/rabbit_variable_queue.erl +++ b/deps/rabbit/src/rabbit_variable_queue.erl @@ -268,6 +268,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include("amqqueue.hrl"). +-include_lib("kernel/include/logger.hrl"). %%---------------------------------------------------------------------------- @@ -382,7 +383,7 @@ stop(VHost) -> ok = rabbit_classic_queue_index_v2:stop(VHost). start_msg_store(VHost, Refs, StartFunState) when is_list(Refs); Refs == undefined -> - rabbit_log:info("Starting message stores for vhost '~ts'", [VHost]), + ?LOG_INFO("Starting message stores for vhost '~ts'", [VHost]), do_start_msg_store(VHost, ?TRANSIENT_MSG_STORE, undefined, ?EMPTY_START_FUN_STATE), do_start_msg_store(VHost, ?PERSISTENT_MSG_STORE, Refs, StartFunState), ok. @@ -390,13 +391,13 @@ start_msg_store(VHost, Refs, StartFunState) when is_list(Refs); Refs == undefine do_start_msg_store(VHost, Type, Refs, StartFunState) -> case rabbit_vhost_msg_store:start(VHost, Type, Refs, StartFunState) of {ok, _} -> - rabbit_log:info("Started message store of type ~ts for vhost '~ts'", [abbreviated_type(Type), VHost]); + ?LOG_INFO("Started message store of type ~ts for vhost '~ts'", [abbreviated_type(Type), VHost]); {error, {no_such_vhost, VHost}} = Err -> - rabbit_log:error("Failed to start message store of type ~ts for vhost '~ts': the vhost no longer exists!", + ?LOG_ERROR("Failed to start message store of type ~ts for vhost '~ts': the vhost no longer exists!", [Type, VHost]), exit(Err); {error, Error} -> - rabbit_log:error("Failed to start message store of type ~ts for vhost '~ts': ~tp", + ?LOG_ERROR("Failed to start message store of type ~ts for vhost '~ts': ~tp", [Type, VHost, Error]), exit({error, Error}) end. @@ -891,7 +892,7 @@ convert_from_v1_to_v2_loop(QueueName, V1Index0, V2Index0, V2Store0, %% Log some progress to keep the user aware of what's going on, as moving %% embedded messages can take quite some time. #resource{virtual_host = VHost, name = Name} = QueueName, - rabbit_log:info("Queue ~ts in vhost ~ts converted ~b messages from v1 to v2", + ?LOG_INFO("Queue ~ts in vhost ~ts converted ~b messages from v1 to v2", [Name, VHost, length(Messages)]), convert_from_v1_to_v2_loop(QueueName, V1Index, V2Index, V2Store, Counters, UpSeqId, HiSeqId, SkipFun). diff --git a/deps/rabbit/src/rabbit_vhost.erl b/deps/rabbit/src/rabbit_vhost.erl index 9a88d38ee43e..7b08e3fec706 100644 --- a/deps/rabbit/src/rabbit_vhost.erl +++ b/deps/rabbit/src/rabbit_vhost.erl @@ -9,6 +9,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include("vhost.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([recover/0, recover/1, read_config/1]). -export([add/2, add/3, add/4, delete/2, delete_ignoring_protection/2, exists/1, assert/1, @@ -40,7 +41,7 @@ recover() -> {Time, _} = timer:tc(fun() -> rabbit_binding:recover() end), - rabbit_log:debug("rabbit_binding:recover/0 completed in ~fs", [Time/1000000]), + ?LOG_DEBUG("rabbit_binding:recover/0 completed in ~fs", [Time/1000000]), %% rabbit_vhost_sup_sup will start the actual recovery. %% So recovery will be run every time a vhost supervisor is restarted. @@ -51,7 +52,7 @@ recover() -> recover(VHost) -> VHostDir = msg_store_dir_path(VHost), - rabbit_log:info("Making sure data directory '~ts' for vhost '~ts' exists", + ?LOG_INFO("Making sure data directory '~ts' for vhost '~ts' exists", [VHostDir, VHost]), VHostStubFile = filename:join(VHostDir, ".vhost"), ok = rabbit_file:ensure_dir(VHostStubFile), @@ -65,25 +66,25 @@ recover(VHost) -> %% we need to add the default type to the metadata case rabbit_db_vhost:get(VHost) of undefined -> - rabbit_log:warning("Cannot check metadata for vhost '~ts' during recovery, record not found.", + ?LOG_WARNING("Cannot check metadata for vhost '~ts' during recovery, record not found.", [VHost]); VHostRecord -> Metadata = vhost:get_metadata(VHostRecord), case maps:is_key(default_queue_type, Metadata) of true -> - rabbit_log:debug("Default queue type for vhost '~ts' is ~p.", + ?LOG_DEBUG("Default queue type for vhost '~ts' is ~p.", [VHost, maps:get(default_queue_type, Metadata)]), ok; false -> DefaultType = rabbit_queue_type:default_alias(), - rabbit_log:info("Setting missing default queue type to '~p' for vhost '~ts'.", + ?LOG_INFO("Setting missing default queue type to '~p' for vhost '~ts'.", [DefaultType, VHost]), case rabbit_db_vhost:merge_metadata(VHost, #{default_queue_type => DefaultType}) of {ok, _UpdatedVHostRecord} -> ok; {error, Reason} -> % Log the error but continue recovery - rabbit_log:warning("Failed to set the default queue type for vhost '~ts': ~p", + ?LOG_WARNING("Failed to set the default queue type for vhost '~ts': ~p", [VHost, Reason]) end end @@ -95,7 +96,7 @@ recover(VHost) -> {Time, ok} = timer:tc(fun() -> rabbit_binding:recover(rabbit_exchange:recover(VHost), QNames) end), - rabbit_log:debug("rabbit_binding:recover/2 for vhost ~ts completed in ~fs", [VHost, Time/1000000]), + ?LOG_DEBUG("rabbit_binding:recover/2 for vhost ~ts completed in ~fs", [VHost, Time/1000000]), ok = rabbit_amqqueue:start(Recovered), ok. @@ -124,7 +125,7 @@ ensure_config_file(VHost) -> _ -> ?LEGACY_INDEX_SEGMENT_ENTRY_COUNT end, - rabbit_log:info("Setting segment_entry_count for vhost '~ts' with ~b queues to '~b'", + ?LOG_INFO("Setting segment_entry_count for vhost '~ts' with ~b queues to '~b'", [VHost, length(QueueDirs), SegmentEntryCount]), file:write_file(Path, io_lib:format( "%% This file is auto-generated! Edit at your own risk!~n" @@ -206,7 +207,7 @@ do_add(Name, Metadata0, ActingUser) -> case Metadata of #{default_queue_type := DQT} -> %% check that the queue type is known - rabbit_log:debug("Default queue type of virtual host '~ts' is ~tp", + ?LOG_DEBUG("Default queue type of virtual host '~ts' is ~tp", [Name, DQT]), try rabbit_queue_type:discover(DQT) of QueueType when is_atom(QueueType) -> @@ -225,9 +226,9 @@ do_add(Name, Metadata0, ActingUser) -> case Description of undefined -> - rabbit_log:info("Adding vhost '~ts' without a description", [Name]); + ?LOG_INFO("Adding vhost '~ts' without a description", [Name]); Description -> - rabbit_log:info("Adding vhost '~ts' (description: '~ts', tags: ~tp)", + ?LOG_INFO("Adding vhost '~ts' (description: '~ts', tags: ~tp)", [Name, Description, Tags]) end, DefaultLimits = rabbit_db_vhost_defaults:list_limits(Name), @@ -235,7 +236,7 @@ do_add(Name, Metadata0, ActingUser) -> {NewOrNot, VHost} = rabbit_db_vhost:create_or_get(Name, DefaultLimits, Metadata), case NewOrNot of new -> - rabbit_log:debug("Inserted a virtual host record ~tp", [VHost]); + ?LOG_DEBUG("Inserted a virtual host record ~tp", [VHost]); existing -> ok end, @@ -280,7 +281,7 @@ declare_default_exchanges(VHostName, ActingUser) -> rabbit_misc:for_each_while_ok( fun({ExchangeName, Type, Internal}) -> Resource = rabbit_misc:r(VHostName, exchange, ExchangeName), - rabbit_log:debug("Will declare an exchange ~tp", [Resource]), + ?LOG_DEBUG("Will declare an exchange ~tp", [Resource]), case rabbit_exchange:declare( Resource, Type, true, false, Internal, [], ActingUser) of @@ -342,7 +343,7 @@ delete(Name, ActingUser) -> case vhost:is_protected_from_deletion(VHost) of true -> Msg = "Refusing to delete virtual host '~ts' because it is protected from deletion", - rabbit_log:debug(Msg, [Name]), + ?LOG_DEBUG(Msg, [Name]), {error, protected_from_deletion}; false -> delete_ignoring_protection(Name, ActingUser) @@ -356,25 +357,25 @@ delete_ignoring_protection(Name, ActingUser) -> %% process, which in turn results in further database actions and %% eventually the termination of that process. Exchange deletion causes %% notifications which must be sent outside the TX - rabbit_log:info("Deleting vhost '~ts'", [Name]), + ?LOG_INFO("Deleting vhost '~ts'", [Name]), %% TODO: This code does a lot of "list resources, walk through the list to %% delete each resource". This feature should be provided by each called %% modules, like `rabbit_amqqueue:delete_all_for_vhost(VHost)'. These new %% calls would be responsible for the atomicity, not this code. %% Clear the permissions first to prohibit new incoming connections when deleting a vhost - rabbit_log:info("Clearing permissions in vhost '~ts' because it's being deleted", [Name]), + ?LOG_INFO("Clearing permissions in vhost '~ts' because it's being deleted", [Name]), ok = rabbit_auth_backend_internal:clear_all_permissions_for_vhost(Name, ActingUser), - rabbit_log:info("Deleting queues in vhost '~ts' because it's being deleted", [Name]), + ?LOG_INFO("Deleting queues in vhost '~ts' because it's being deleted", [Name]), QDelFun = fun (Q) -> rabbit_amqqueue:delete(Q, false, false, ActingUser) end, [begin QName = amqqueue:get_name(Q), assert_benign(rabbit_amqqueue:with(QName, QDelFun), ActingUser) end || Q <- rabbit_amqqueue:list(Name)], - rabbit_log:info("Deleting exchanges in vhost '~ts' because it's being deleted", [Name]), + ?LOG_INFO("Deleting exchanges in vhost '~ts' because it's being deleted", [Name]), ok = rabbit_exchange:delete_all(Name, ActingUser), - rabbit_log:info("Clearing policies and runtime parameters in vhost '~ts' because it's being deleted", [Name]), + ?LOG_INFO("Clearing policies and runtime parameters in vhost '~ts' because it's being deleted", [Name]), _ = rabbit_runtime_parameters:clear_vhost(Name, ActingUser), - rabbit_log:debug("Removing vhost '~ts' from the metadata storage because it's being deleted", [Name]), + ?LOG_DEBUG("Removing vhost '~ts' from the metadata storage because it's being deleted", [Name]), Ret = case rabbit_db_vhost:delete(Name) of true -> ok = rabbit_event:notify( @@ -407,7 +408,7 @@ put_vhost(Name, Description, Tags0, DefaultQueueType, Trace, Username) -> Other -> Other end, ParsedTags = parse_tags(Tags), - rabbit_log:debug("Parsed virtual host tags ~tp to ~tp", [Tags, ParsedTags]), + ?LOG_DEBUG("Parsed virtual host tags ~tp to ~tp", [Tags, ParsedTags]), Result = case exists(Name) of true -> update(Name, Description, ParsedTags, DefaultQueueType, Username); @@ -451,7 +452,7 @@ is_over_vhost_limit(Name, Limit) when is_integer(Limit) -> ErrorMsg = rabbit_misc:format("cannot create vhost '~ts': " "vhost limit of ~tp is reached", [Name, Limit]), - rabbit_log:error(ErrorMsg), + ?LOG_ERROR(ErrorMsg), exit({vhost_limit_exceeded, ErrorMsg}) end. @@ -510,7 +511,7 @@ vhost_cluster_state(VHost) -> Nodes). vhost_down(VHost) -> - rabbit_log:info("Virtual host '~ts' is stopping", [VHost]), + ?LOG_INFO("Virtual host '~ts' is stopping", [VHost]), ok = rabbit_event:notify(vhost_down, [{name, VHost}, {node, node()}, @@ -518,16 +519,16 @@ vhost_down(VHost) -> delete_storage(VHost) -> VhostDir = msg_store_dir_path(VHost), - rabbit_log:info("Deleting message store directory for vhost '~ts' at '~ts'", [VHost, VhostDir]), + ?LOG_INFO("Deleting message store directory for vhost '~ts' at '~ts'", [VHost, VhostDir]), %% Message store should be closed when vhost supervisor is closed. case rabbit_file:recursive_delete([VhostDir]) of ok -> ok; {error, {_, enoent}} -> %% a concurrent delete did the job for us - rabbit_log:warning("Tried to delete storage directories for vhost '~ts', it failed with an ENOENT", [VHost]), + ?LOG_WARNING("Tried to delete storage directories for vhost '~ts', it failed with an ENOENT", [VHost]), ok; Other -> - rabbit_log:warning("Tried to delete storage directories for vhost '~ts': ~tp", [VHost, Other]), + ?LOG_WARNING("Tried to delete storage directories for vhost '~ts': ~tp", [VHost, Other]), Other end. @@ -642,7 +643,7 @@ update_tags(VHostName, Tags, ActingUser) -> end, VHost = rabbit_db_vhost:set_tags(VHostName, Tags), ConvertedTags = vhost:get_tags(VHost), - rabbit_log:info("Successfully set tags for virtual host '~ts' to ~tp", [VHostName, ConvertedTags]), + ?LOG_INFO("Successfully set tags for virtual host '~ts' to ~tp", [VHostName, ConvertedTags]), rabbit_event:notify_if(are_different(CurrentTags, ConvertedTags), vhost_tags_set, [{name, VHostName}, {tags, ConvertedTags}, @@ -650,13 +651,13 @@ update_tags(VHostName, Tags, ActingUser) -> VHost catch throw:{error, {no_such_vhost, _}} = Error -> - rabbit_log:warning("Failed to set tags for virtual host '~ts': the virtual host does not exist", [VHostName]), + ?LOG_WARNING("Failed to set tags for virtual host '~ts': the virtual host does not exist", [VHostName]), throw(Error); throw:Error -> - rabbit_log:warning("Failed to set tags for virtual host '~ts': ~tp", [VHostName, Error]), + ?LOG_WARNING("Failed to set tags for virtual host '~ts': ~tp", [VHostName, Error]), throw(Error); exit:Error -> - rabbit_log:warning("Failed to set tags for virtual host '~ts': ~tp", [VHostName, Error]), + ?LOG_WARNING("Failed to set tags for virtual host '~ts': ~tp", [VHostName, Error]), exit(Error) end. @@ -718,7 +719,7 @@ i(metadata, VHost) -> M#{default_queue_type => DQT} end; i(Item, VHost) -> - rabbit_log:error("Don't know how to compute a virtual host info item '~ts' for virtual host '~tp'", [Item, VHost]), + ?LOG_ERROR("Don't know how to compute a virtual host info item '~ts' for virtual host '~tp'", [Item, VHost]), throw({bad_argument, Item}). -spec info(vhost:vhost() | vhost:name()) -> rabbit_types:infos(). diff --git a/deps/rabbit/src/rabbit_vhost_msg_store.erl b/deps/rabbit/src/rabbit_vhost_msg_store.erl index 1211f6c039db..e7f6fe2c59e7 100644 --- a/deps/rabbit/src/rabbit_vhost_msg_store.erl +++ b/deps/rabbit/src/rabbit_vhost_msg_store.erl @@ -8,6 +8,7 @@ -module(rabbit_vhost_msg_store). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([start/4, stop/2, client_init/4, successfully_recovered_state/2]). -export([vhost_store_pid/2]). @@ -25,7 +26,7 @@ start(VHost, Type, ClientRefs, StartupFunState) when is_list(ClientRefs); %% we can get here if a vhost is added and removed concurrently %% e.g. some integration tests do it {error, {no_such_vhost, VHost}} = E -> - rabbit_log:error("Failed to start a message store for vhost ~ts: vhost no longer exists!", + ?LOG_ERROR("Failed to start a message store for vhost ~ts: vhost no longer exists!", [VHost]), E end. @@ -37,7 +38,7 @@ stop(VHost, Type) -> ok = supervisor:delete_child(VHostSup, Type); %% see start/4 {error, {no_such_vhost, VHost}} -> - rabbit_log:error("Failed to stop a message store for vhost ~ts: vhost no longer exists!", + ?LOG_ERROR("Failed to stop a message store for vhost ~ts: vhost no longer exists!", [VHost]), ok diff --git a/deps/rabbit/src/rabbit_vhost_process.erl b/deps/rabbit/src/rabbit_vhost_process.erl index 38d5392792dd..42e5f45c798c 100644 --- a/deps/rabbit/src/rabbit_vhost_process.erl +++ b/deps/rabbit/src/rabbit_vhost_process.erl @@ -21,6 +21,9 @@ -module(rabbit_vhost_process). +-include_lib("kernel/include/logger.hrl"). + + -define(VHOST_CHECK_INTERVAL, 5000). -behaviour(gen_server2). @@ -35,7 +38,7 @@ start_link(VHost) -> init([VHost]) -> process_flag(trap_exit, true), - rabbit_log:debug("Recovering data for virtual host ~ts", [VHost]), + ?LOG_DEBUG("Recovering data for virtual host ~ts", [VHost]), try %% Recover the vhost data and save it to vhost registry. ok = rabbit_vhost:recover(VHost), @@ -45,7 +48,7 @@ init([VHost]) -> {ok, VHost} catch _:Reason:Stacktrace -> rabbit_amqqueue:mark_local_durable_queues_stopped(VHost), - rabbit_log:error("Unable to recover vhost ~tp data. Reason ~tp~n" + ?LOG_ERROR("Unable to recover vhost ~tp data. Reason ~tp~n" " Stacktrace ~tp", [VHost, Reason, Stacktrace]), {stop, Reason} @@ -61,7 +64,7 @@ handle_info(check_vhost, VHost) -> case rabbit_vhost:exists(VHost) of true -> {noreply, VHost}; false -> - rabbit_log:warning("Virtual host '~ts' is gone. " + ?LOG_WARNING("Virtual host '~ts' is gone. " "Stopping its top level supervisor.", [VHost]), %% Stop vhost's top supervisor in a one-off process to avoid a deadlock: diff --git a/deps/rabbit/src/rabbit_vhost_sup_sup.erl b/deps/rabbit/src/rabbit_vhost_sup_sup.erl index 8778f3d2c542..95864684db2f 100644 --- a/deps/rabbit/src/rabbit_vhost_sup_sup.erl +++ b/deps/rabbit/src/rabbit_vhost_sup_sup.erl @@ -8,6 +8,7 @@ -module(rabbit_vhost_sup_sup). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(supervisor). @@ -79,18 +80,18 @@ delete_on_all_nodes(VHost) -> stop_and_delete_vhost(VHost) -> StopResult = case lookup_vhost_sup_record(VHost) of not_found -> - rabbit_log:warning("Supervisor for vhost '~ts' not found during deletion procedure", + ?LOG_WARNING("Supervisor for vhost '~ts' not found during deletion procedure", [VHost]), ok; #vhost_sup{wrapper_pid = WrapperPid, vhost_sup_pid = VHostSupPid} -> case is_process_alive(WrapperPid) of false -> - rabbit_log:info("Supervisor ~tp for vhost '~ts' already stopped", + ?LOG_INFO("Supervisor ~tp for vhost '~ts' already stopped", [VHostSupPid, VHost]), ok; true -> - rabbit_log:info("Stopping vhost supervisor ~tp" + ?LOG_INFO("Stopping vhost supervisor ~tp" " for vhost '~ts'", [VHostSupPid, VHost]), case supervisor:terminate_child(?MODULE, WrapperPid) of @@ -112,7 +113,7 @@ stop_and_delete_vhost(VHost, Node) -> case rabbit_misc:rpc_call(Node, rabbit_vhost_sup_sup, stop_and_delete_vhost, [VHost]) of ok -> ok; {badrpc, RpcErr} -> - rabbit_log:error("Failed to stop and delete a vhost ~tp" + ?LOG_ERROR("Failed to stop and delete a vhost ~tp" " on node ~tp." " Reason: ~tp", [VHost, Node, RpcErr]), @@ -124,7 +125,7 @@ init_vhost(VHost) -> case start_vhost(VHost) of {ok, _} -> ok; {error, {already_started, _}} -> - rabbit_log:warning( + ?LOG_WARNING( "Attempting to start an already started vhost '~ts'.", [VHost]), ok; @@ -133,13 +134,13 @@ init_vhost(VHost) -> {error, Reason} -> case vhost_restart_strategy() of permanent -> - rabbit_log:error( + ?LOG_ERROR( "Unable to initialize vhost data store for vhost '~ts'." " Reason: ~tp", [VHost, Reason]), throw({error, Reason}); transient -> - rabbit_log:warning( + ?LOG_WARNING( "Unable to initialize vhost data store for vhost '~ts'." " The vhost will be stopped for this node. " " Reason: ~tp", diff --git a/deps/rabbit/src/rabbit_vhosts.erl b/deps/rabbit/src/rabbit_vhosts.erl index dc1734c9a96d..e8bac94cb581 100644 --- a/deps/rabbit/src/rabbit_vhosts.erl +++ b/deps/rabbit/src/rabbit_vhosts.erl @@ -9,6 +9,9 @@ %% several others virtual hosts-related modules. -module(rabbit_vhosts). +-include_lib("kernel/include/logger.hrl"). + + -define(PERSISTENT_TERM_COUNTER_KEY, rabbit_vhosts_reconciliation_run_counter). %% API @@ -63,11 +66,11 @@ reconcile() -> %% See start_processes_for_all/1. -spec reconcile_once() -> 'ok'. reconcile_once() -> - rabbit_log:debug("Will reconcile virtual host processes on all cluster members..."), + ?LOG_DEBUG("Will reconcile virtual host processes on all cluster members..."), _ = start_processes_for_all(), _ = increment_run_counter(), N = get_run_counter(), - rabbit_log:debug("Done with virtual host processes reconciliation (run ~tp)", [N]), + ?LOG_DEBUG("Done with virtual host processes reconciliation (run ~tp)", [N]), ok. -spec on_node_up(Node :: node()) -> 'ok'. @@ -77,7 +80,7 @@ on_node_up(_Node) -> true -> DelayInSeconds = 10, Delay = DelayInSeconds * 1000, - rabbit_log:debug("Will reschedule virtual host process reconciliation after ~b seconds", [DelayInSeconds]), + ?LOG_DEBUG("Will reschedule virtual host process reconciliation after ~b seconds", [DelayInSeconds]), _ = timer:apply_after(Delay, ?MODULE, reconcile_once, []), ok end. @@ -111,13 +114,13 @@ reconciliation_interval() -> start_processes_for_all(Nodes) -> Names = list_names(), N = length(Names), - rabbit_log:debug("Will make sure that processes of ~p virtual hosts are running on all reachable cluster nodes", [N]), + ?LOG_DEBUG("Will make sure that processes of ~p virtual hosts are running on all reachable cluster nodes", [N]), [begin try start_on_all_nodes(VH, Nodes) catch _:Err:_Stacktrace -> - rabbit_log:error("Could not reconcile virtual host ~ts: ~tp", [VH, Err]) + ?LOG_ERROR("Could not reconcile virtual host ~ts: ~tp", [VH, Err]) end end || VH <- Names], ok. @@ -153,14 +156,14 @@ maybe_start_timer(FunName) -> case N >= 10 of true -> %% Stop after ten runs - rabbit_log:debug("Will stop virtual host process reconciliation after ~tp runs", [N]), + ?LOG_DEBUG("Will stop virtual host process reconciliation after ~tp runs", [N]), ok; false -> case is_reconciliation_enabled() of false -> ok; true -> Delay = DelayInSeconds * 1000, - rabbit_log:debug("Will reschedule virtual host process reconciliation after ~b seconds", [DelayInSeconds]), + ?LOG_DEBUG("Will reschedule virtual host process reconciliation after ~b seconds", [DelayInSeconds]), timer:apply_after(Delay, ?MODULE, FunName, []) end end. diff --git a/deps/rabbit/src/vm_memory_monitor.erl b/deps/rabbit/src/vm_memory_monitor.erl index e97a468372f4..b3d119e6b1c8 100644 --- a/deps/rabbit/src/vm_memory_monitor.erl +++ b/deps/rabbit/src/vm_memory_monitor.erl @@ -55,6 +55,7 @@ proc_file = undefined}). -include("include/rabbit_memory.hrl"). +-include_lib("kernel/include/logger.hrl"). %%---------------------------------------------------------------------------- @@ -89,7 +90,7 @@ get_total_memory() -> {ok, ParsedTotal} -> ParsedTotal; {error, parse_error} -> - rabbit_log:warning( + ?LOG_WARNING( "The override value for the total memmory available is " "not a valid value: ~tp, getting total from the system.", [Value]), @@ -163,7 +164,7 @@ get_memory_calculation_strategy() -> legacy -> erlang; %% backwards compatibility rss -> rss; UnsupportedValue -> - rabbit_log:warning( + ?LOG_WARNING( "Unsupported value '~tp' for vm_memory_calculation_strategy. " "Supported values: (allocated|erlang|legacy|rss). " "Defaulting to 'rss'", @@ -252,7 +253,7 @@ get_cached_process_memory_and_limit() -> try gen_server:call(?MODULE, get_cached_process_memory_and_limit, infinity) catch exit:{noproc, Error} -> - rabbit_log:warning("Memory monitor process not yet started: ~tp", [Error]), + ?LOG_WARNING("Memory monitor process not yet started: ~tp", [Error]), ProcessMemory = get_process_memory_uncached(), {ProcessMemory, infinity} end. @@ -306,7 +307,7 @@ get_total_memory_from_os() -> try get_total_memory(os:type()) catch _:Error:Stacktrace -> - rabbit_log:warning( + ?LOG_WARNING( "Failed to get total system memory: ~n~tp~n~tp", [Error, Stacktrace]), unknown @@ -317,7 +318,7 @@ set_mem_limits(State, {relative, MemLimit}) -> set_mem_limits(State, MemLimit) -> case erlang:system_info(wordsize) of 4 -> - rabbit_log:warning( + ?LOG_WARNING( "You are using a 32-bit version of Erlang: you may run into " "memory address~n" "space exhaustion or statistic counters overflow.~n"); @@ -330,7 +331,7 @@ set_mem_limits(State, MemLimit) -> case State of #state { total_memory = undefined, memory_limit = undefined } -> - rabbit_log:warning( + ?LOG_WARNING( "Unknown total memory size for your OS ~tp. " "Assuming memory size is ~tp MiB (~tp bytes).", [os:type(), @@ -345,7 +346,7 @@ set_mem_limits(State, MemLimit) -> UsableMemory = case get_vm_limit() of Limit when Limit < TotalMemory -> - rabbit_log:warning( + ?LOG_WARNING( "Only ~tp MiB (~tp bytes) of ~tp MiB (~tp bytes) memory usable due to " "limited address space.~n" "Crashes due to memory exhaustion are possible - see~n" @@ -357,7 +358,7 @@ set_mem_limits(State, MemLimit) -> TotalMemory end, MemLim = interpret_limit(parse_mem_limit(MemLimit), UsableMemory), - rabbit_log:info( + ?LOG_INFO( "Memory high watermark set to ~tp MiB (~tp bytes)" " of ~tp MiB (~tp bytes) total", [trunc(MemLim/?ONE_MiB), MemLim, @@ -381,7 +382,7 @@ parse_mem_limit({absolute, Limit}) -> case rabbit_resource_monitor_misc:parse_information_unit(Limit) of {ok, ParsedLimit} -> {absolute, ParsedLimit}; {error, parse_error} -> - rabbit_log:error("Unable to parse vm_memory_high_watermark value ~tp", [Limit]), + ?LOG_ERROR("Unable to parse vm_memory_high_watermark value ~tp", [Limit]), ?DEFAULT_VM_MEMORY_HIGH_WATERMARK end; parse_mem_limit({relative, MemLimit}) -> @@ -391,13 +392,13 @@ parse_mem_limit(MemLimit) when is_integer(MemLimit) -> parse_mem_limit(MemLimit) when is_float(MemLimit), MemLimit =< ?MAX_VM_MEMORY_HIGH_WATERMARK -> MemLimit; parse_mem_limit(MemLimit) when is_float(MemLimit), MemLimit > ?MAX_VM_MEMORY_HIGH_WATERMARK -> - rabbit_log:warning( + ?LOG_WARNING( "Memory high watermark of ~tp is above the allowed maximum, falling back to ~tp", [MemLimit, ?MAX_VM_MEMORY_HIGH_WATERMARK] ), ?MAX_VM_MEMORY_HIGH_WATERMARK; parse_mem_limit(MemLimit) -> - rabbit_log:warning( + ?LOG_WARNING( "Memory high watermark of ~tp is invalid, defaulting to ~tp", [MemLimit, ?DEFAULT_VM_MEMORY_HIGH_WATERMARK] ), @@ -419,7 +420,7 @@ internal_update(State0 = #state{memory_limit = MemLimit, State1#state{alarmed = NewAlarmed}. emit_update_info(AlarmState, MemUsed, MemLimit) -> - rabbit_log:info( + ?LOG_INFO( "vm_memory_high_watermark ~tp. Memory used:~tp allowed:~tp", [AlarmState, MemUsed, MemLimit]). @@ -458,7 +459,7 @@ cmd(Command, ThrowIfMissing) -> end. default_linux_pagesize(CmdOutput) -> - rabbit_log:warning( + ?LOG_WARNING( "Failed to get memory page size, using 4096. Reason: ~ts", [CmdOutput]), 4096. @@ -583,7 +584,7 @@ sysctl(Def) -> list_to_integer(R) catch error:badarg -> - rabbit_log:debug("Failed to get total system memory: ~tp", [R]), + ?LOG_DEBUG("Failed to get total system memory: ~tp", [R]), unknown end. diff --git a/deps/rabbit/test/unit_log_management_SUITE.erl b/deps/rabbit/test/unit_log_management_SUITE.erl index 4b449af84d18..6ee6b18b8b23 100644 --- a/deps/rabbit/test/unit_log_management_SUITE.erl +++ b/deps/rabbit/test/unit_log_management_SUITE.erl @@ -12,6 +12,7 @@ -include_lib("kernel/include/file.hrl"). -include_lib("amqp_client/include/amqp_client.hrl"). -include_lib("rabbitmq_ct_helpers/include/rabbit_assert.hrl"). +-include_lib("kernel/include/logger.hrl"). -compile(export_all). @@ -227,7 +228,7 @@ non_empty_files(Files) -> end || EmptyFile <- empty_files(Files)]. test_logs_working(LogFiles) -> - ok = rabbit_log:error("Log a test message"), + ok = ?LOG_ERROR("Log a test message"), %% give the error loggers some time to catch up ?awaitMatch(true, lists:all(fun(LogFile) -> [true] =:= non_empty_files([LogFile]) end, LogFiles), diff --git a/deps/rabbit_common/codegen.py b/deps/rabbit_common/codegen.py index ebb36cf24b6e..ce752fbd95d7 100755 --- a/deps/rabbit_common/codegen.py +++ b/deps/rabbit_common/codegen.py @@ -534,7 +534,7 @@ def genAmqpException(c,v,cls): for (c,v,cls) in spec.constants: genLookupException(c,v,cls) print("lookup_amqp_exception(Code) ->") - print(" rabbit_log:warning(\"Unknown AMQP error code '~p'~n\", [Code]),") + print(" ?LOG_WARNING(\"Unknown AMQP error code '~p'~n\", [Code]),") print(" {true, ?INTERNAL_ERROR, <<\"INTERNAL_ERROR\">>}.") for(c,v,cls) in spec.constants: genAmqpException(c,v,cls) diff --git a/deps/rabbit_common/src/app_utils.erl b/deps/rabbit_common/src/app_utils.erl index bc28861ed717..66d42cd00a26 100644 --- a/deps/rabbit_common/src/app_utils.erl +++ b/deps/rabbit_common/src/app_utils.erl @@ -7,6 +7,9 @@ -module(app_utils). +-include_lib("kernel/include/logger.hrl"). + + -export([load_applications/1, start_applications/1, start_applications/2, start_applications/3, stop_applications/1, stop_applications/2, app_dependency_order/2, @@ -61,7 +64,7 @@ start_applications(Apps, ErrorHandler, RestartTypes) -> stop_applications(Apps, ErrorHandler) -> manage_applications(fun lists:foldr/3, fun(App) -> - rabbit_log:info("Stopping application '~ts'", [App]), + ?LOG_INFO("Stopping application '~ts'", [App]), application:stop(App) end, fun(App) -> ensure_all_started(App, #{}) end, diff --git a/deps/rabbit_common/src/rabbit_amqp_connection.erl b/deps/rabbit_common/src/rabbit_amqp_connection.erl index 37cc408c5463..cd99f4d1fed2 100644 --- a/deps/rabbit_common/src/rabbit_amqp_connection.erl +++ b/deps/rabbit_common/src/rabbit_amqp_connection.erl @@ -7,6 +7,9 @@ -module(rabbit_amqp_connection). +-include_lib("kernel/include/logger.hrl"). + + -export([amqp_params/2]). -spec amqp_params(pid(), timeout()) -> [{atom(), term()}]. @@ -14,11 +17,11 @@ amqp_params(ConnPid, Timeout) -> P = try gen_server:call(ConnPid, {info, [amqp_params]}, Timeout) catch exit:{noproc, Error} -> - rabbit_log:debug("file ~tp, line ~tp - connection process ~tp not alive: ~tp", + ?LOG_DEBUG("file ~tp, line ~tp - connection process ~tp not alive: ~tp", [?FILE, ?LINE, ConnPid, Error]), []; _:Error -> - rabbit_log:debug("file ~tp, line ~tp - failed to get amqp_params from connection process ~tp: ~tp", + ?LOG_DEBUG("file ~tp, line ~tp - failed to get amqp_params from connection process ~tp: ~tp", [?FILE, ?LINE, ConnPid, Error]), [] end, diff --git a/deps/rabbit_common/src/rabbit_binary_generator.erl b/deps/rabbit_common/src/rabbit_binary_generator.erl index e1a0aa23d763..f5cf8a03a040 100644 --- a/deps/rabbit_common/src/rabbit_binary_generator.erl +++ b/deps/rabbit_common/src/rabbit_binary_generator.erl @@ -8,6 +8,7 @@ -module(rabbit_binary_generator). -include("rabbit_framing.hrl"). -include("rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([build_simple_method_frame/3, build_simple_content_frames/4, @@ -223,7 +224,7 @@ lookup_amqp_exception(#amqp_error{name = Name, ExplBin = amqp_exception_explanation(Text, Expl), {ShouldClose, Code, ExplBin, Method}; lookup_amqp_exception(Other, Protocol) -> - rabbit_log:warning("Non-AMQP exit reason '~tp'", [Other]), + ?LOG_WARNING("Non-AMQP exit reason '~tp'", [Other]), {ShouldClose, Code, Text} = Protocol:lookup_amqp_exception(internal_error), {ShouldClose, Code, Text, none}. diff --git a/deps/rabbit_common/src/rabbit_env.erl b/deps/rabbit_common/src/rabbit_env.erl index 8440dc6b1c76..49f4ad0a5e1e 100644 --- a/deps/rabbit_common/src/rabbit_env.erl +++ b/deps/rabbit_common/src/rabbit_env.erl @@ -1724,7 +1724,7 @@ collect_conf_env_file_output(Context, Port, Marker, Output) -> collect_conf_env_file_output( Context, Port, Marker, [Output, UnicodeChunk]); {Port, {data, Chunk}} -> - rabbit_log:warning("~tp unexpected non-binary chunk in " + ?LOG_WARNING("~tp unexpected non-binary chunk in " "conf env file output: ~tp~n", [?MODULE, Chunk]) end. @@ -2157,5 +2157,5 @@ unicode_characters_to_list(Input) -> end. log_characters_to_list_error(Input, Partial, Rest) -> - rabbit_log:error("error converting '~tp' to unicode string " + ?LOG_ERROR("error converting '~tp' to unicode string " "(partial '~tp', rest '~tp')", [Input, Partial, Rest]). diff --git a/deps/rabbit_common/src/rabbit_framing_amqp_0_8.erl b/deps/rabbit_common/src/rabbit_framing_amqp_0_8.erl index c4c53ecdd93c..cdeb26db2e82 100644 --- a/deps/rabbit_common/src/rabbit_framing_amqp_0_8.erl +++ b/deps/rabbit_common/src/rabbit_framing_amqp_0_8.erl @@ -8,6 +8,7 @@ %% -module(rabbit_framing_amqp_0_8). -include("rabbit_framing.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([version/0]). -export([lookup_method_name/1]). @@ -1626,7 +1627,7 @@ lookup_amqp_exception(not_allowed) -> {true, ?NOT_ALLOWED, <<"NOT_ALLOWED">>}; lookup_amqp_exception(not_implemented) -> {true, ?NOT_IMPLEMENTED, <<"NOT_IMPLEMENTED">>}; lookup_amqp_exception(internal_error) -> {true, ?INTERNAL_ERROR, <<"INTERNAL_ERROR">>}; lookup_amqp_exception(Code) -> - rabbit_log:warning("Unknown AMQP error code '~p'~n", [Code]), + ?LOG_WARNING("Unknown AMQP error code '~p'~n", [Code]), {true, ?INTERNAL_ERROR, <<"INTERNAL_ERROR">>}. amqp_exception(?FRAME_METHOD) -> frame_method; amqp_exception(?FRAME_HEADER) -> frame_header; diff --git a/deps/rabbit_common/src/rabbit_framing_amqp_0_9_1.erl b/deps/rabbit_common/src/rabbit_framing_amqp_0_9_1.erl index 644af8d90496..3f0b13a2683e 100644 --- a/deps/rabbit_common/src/rabbit_framing_amqp_0_9_1.erl +++ b/deps/rabbit_common/src/rabbit_framing_amqp_0_9_1.erl @@ -8,6 +8,7 @@ %% -module(rabbit_framing_amqp_0_9_1). -include("rabbit_framing.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([version/0]). -export([lookup_method_name/1]). @@ -1240,7 +1241,7 @@ lookup_amqp_exception(not_allowed) -> {true, ?NOT_ALLOWED, <<"NOT_ALLOWED">>}; lookup_amqp_exception(not_implemented) -> {true, ?NOT_IMPLEMENTED, <<"NOT_IMPLEMENTED">>}; lookup_amqp_exception(internal_error) -> {true, ?INTERNAL_ERROR, <<"INTERNAL_ERROR">>}; lookup_amqp_exception(Code) -> - rabbit_log:warning("Unknown AMQP error code '~p'~n", [Code]), + ?LOG_WARNING("Unknown AMQP error code '~p'~n", [Code]), {true, ?INTERNAL_ERROR, <<"INTERNAL_ERROR">>}. amqp_exception(?FRAME_METHOD) -> frame_method; amqp_exception(?FRAME_HEADER) -> frame_header; diff --git a/deps/rabbit_common/src/rabbit_log.erl b/deps/rabbit_common/src/rabbit_log.erl deleted file mode 100644 index 65fef24ce173..000000000000 --- a/deps/rabbit_common/src/rabbit_log.erl +++ /dev/null @@ -1,118 +0,0 @@ -%% This Source Code Form is subject to the terms of the Mozilla Public -%% License, v. 2.0. If a copy of the MPL was not distributed with this -%% file, You can obtain one at https://mozilla.org/MPL/2.0/. -%% -%% Copyright (c) 2007-2025 Broadcom. All Rights Reserved. The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. All rights reserved. -%% - --module(rabbit_log). - --export([log/3, log/4]). --export([debug/1, debug/2, debug/3, - info/1, info/2, info/3, - notice/1, notice/2, notice/3, - warning/1, warning/2, warning/3, - error/1, error/2, error/3, - critical/1, critical/2, critical/3, - alert/1, alert/2, alert/3, - emergency/1, emergency/2, emergency/3, - none/1, none/2, none/3]). - --include("logging.hrl"). - --compile({no_auto_import, [error/2, error/3]}). - -%%---------------------------------------------------------------------------- - --type category() :: atom(). - --spec debug(string()) -> 'ok'. --spec debug(string(), [any()]) -> 'ok'. --spec debug(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec info(string()) -> 'ok'. --spec info(string(), [any()]) -> 'ok'. --spec info(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec notice(string()) -> 'ok'. --spec notice(string(), [any()]) -> 'ok'. --spec notice(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec warning(string()) -> 'ok'. --spec warning(string(), [any()]) -> 'ok'. --spec warning(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec error(string()) -> 'ok'. --spec error(string(), [any()]) -> 'ok'. --spec error(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec critical(string()) -> 'ok'. --spec critical(string(), [any()]) -> 'ok'. --spec critical(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec alert(string()) -> 'ok'. --spec alert(string(), [any()]) -> 'ok'. --spec alert(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec emergency(string()) -> 'ok'. --spec emergency(string(), [any()]) -> 'ok'. --spec emergency(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec none(string()) -> 'ok'. --spec none(string(), [any()]) -> 'ok'. --spec none(pid() | [tuple()], string(), [any()]) -> 'ok'. - -%%---------------------------------------------------------------------------- - --spec log(category(), logger:level(), string()) -> 'ok'. -log(Category, Level, Fmt) -> log(Category, Level, Fmt, []). - --spec log(category(), logger:level(), string(), [any()]) -> 'ok'. -log(default, Level, Fmt, Args) when is_list(Args) -> - logger:log(Level, Fmt, Args, #{domain => ?RMQLOG_DOMAIN_GLOBAL}); -log(Category, Level, Fmt, Args) when is_list(Args) -> - logger:log(Level, Fmt, Args, #{domain => ?DEFINE_RMQLOG_DOMAIN(Category)}). - -debug(Format) -> debug(Format, []). -debug(Format, Args) -> debug(self(), Format, Args). -debug(Pid, Format, Args) -> - logger:debug(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_GLOBAL}). - -info(Format) -> info(Format, []). -info(Format, Args) -> info(self(), Format, Args). -info(Pid, Format, Args) -> - logger:info(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_GLOBAL}). - -notice(Format) -> notice(Format, []). -notice(Format, Args) -> notice(self(), Format, Args). -notice(Pid, Format, Args) -> - logger:notice(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_GLOBAL}). - -warning(Format) -> warning(Format, []). -warning(Format, Args) -> warning(self(), Format, Args). -warning(Pid, Format, Args) -> - logger:warning(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_GLOBAL}). - -error(Format) -> error(Format, []). -error(Format, Args) -> error(self(), Format, Args). -error(Pid, Format, Args) -> - logger:error(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_GLOBAL}). - -critical(Format) -> critical(Format, []). -critical(Format, Args) -> critical(self(), Format, Args). -critical(Pid, Format, Args) -> - logger:critical(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_GLOBAL}). - -alert(Format) -> alert(Format, []). -alert(Format, Args) -> alert(self(), Format, Args). -alert(Pid, Format, Args) -> - logger:alert(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_GLOBAL}). - -emergency(Format) -> emergency(Format, []). -emergency(Format, Args) -> emergency(self(), Format, Args). -emergency(Pid, Format, Args) -> - logger:emergency(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_GLOBAL}). - -none(_Format) -> ok. -none(_Format, _Args) -> ok. -none(_Pid, _Format, _Args) -> ok. diff --git a/deps/rabbit_common/src/rabbit_misc.erl b/deps/rabbit_common/src/rabbit_misc.erl index 09ff33a8cab2..93be44a6388c 100644 --- a/deps/rabbit_common/src/rabbit_misc.erl +++ b/deps/rabbit_common/src/rabbit_misc.erl @@ -13,6 +13,7 @@ -include("rabbit_misc.hrl"). -include_lib("kernel/include/file.hrl"). +-include_lib("kernel/include/logger.hrl"). -ifdef(TEST). -export([decompose_pid/1, compose_pid/4]). @@ -1284,7 +1285,7 @@ safe_ets_update_counter(Tab, Key, UpdateOp) -> try ets:update_counter(Tab, Key, UpdateOp) catch error:badarg:E -> - rabbit_log:debug("error updating ets counter ~p in table ~p: ~p", [Key, Tab, E]), + ?LOG_DEBUG("error updating ets counter ~p in table ~p: ~p", [Key, Tab, E]), ok end. @@ -1354,7 +1355,7 @@ safe_ets_update_counter(Tab, Key, UpdateOp, OnSuccess, OnFailure) -> try OnSuccess(ets:update_counter(Tab, Key, UpdateOp)) catch error:badarg:E -> - rabbit_log:debug("error updating ets counter ~p in table ~p: ~p", [Key, Tab, E]), + ?LOG_DEBUG("error updating ets counter ~p in table ~p: ~p", [Key, Tab, E]), OnFailure() end. @@ -1373,7 +1374,7 @@ safe_ets_update_element(Tab, Key, ElementSpec) -> try ets:update_element(Tab, Key, ElementSpec) catch error:badarg:E -> - rabbit_log:debug("error updating ets element ~p in table ~p: ~p", [Key, Tab, E]), + ?LOG_DEBUG("error updating ets element ~p in table ~p: ~p", [Key, Tab, E]), false end. @@ -1410,7 +1411,7 @@ safe_ets_update_element(Tab, Key, ElementSpec, OnSuccess, OnFailure) -> try OnSuccess(ets:update_element(Tab, Key, ElementSpec)) catch error:badarg:E -> - rabbit_log:debug("error updating ets element ~p in table ~p: ~p", [Key, Tab, E]), + ?LOG_DEBUG("error updating ets element ~p in table ~p: ~p", [Key, Tab, E]), OnFailure(), false end. diff --git a/deps/rabbit_common/src/rabbit_nodes_common.erl b/deps/rabbit_common/src/rabbit_nodes_common.erl index 310ce29d23fc..1e9a8dbcee3e 100644 --- a/deps/rabbit_common/src/rabbit_nodes_common.erl +++ b/deps/rabbit_common/src/rabbit_nodes_common.erl @@ -14,6 +14,7 @@ -define(ERROR_LOGGER_HANDLER, rabbit_error_logger_handler). -include_lib("kernel/include/inet.hrl"). +-include_lib("kernel/include/logger.hrl"). %% %% API @@ -51,7 +52,7 @@ names(Hostname) -> names(Hostname, 0) -> epmd_names(Hostname); names(Hostname, RetriesLeft) -> - rabbit_log:debug("Getting epmd names for hostname '~ts', ~b retries left", + ?LOG_DEBUG("Getting epmd names for hostname '~ts', ~b retries left", [Hostname, RetriesLeft]), case catch epmd_names(Hostname) of {ok, R } -> {ok, R}; @@ -131,7 +132,7 @@ port_shutdown_loop(Port) -> {Port, closed} -> ok; {Port, {data, _}} -> port_shutdown_loop(Port); {'EXIT', Port, Reason} -> - rabbit_log:error("Failed to start a one-off Erlang VM to keep epmd alive: ~tp", [Reason]) + ?LOG_ERROR("Failed to start a one-off Erlang VM to keep epmd alive: ~tp", [Reason]) after 15000 -> %% ensure the port is closed Port ! {self(), close}, diff --git a/deps/rabbit_common/src/rabbit_ssl_options.erl b/deps/rabbit_common/src/rabbit_ssl_options.erl index 2916e92d3d8d..49df82f8fc0c 100644 --- a/deps/rabbit_common/src/rabbit_ssl_options.erl +++ b/deps/rabbit_common/src/rabbit_ssl_options.erl @@ -7,6 +7,9 @@ -module(rabbit_ssl_options). +-include_lib("kernel/include/logger.hrl"). + + -export([ fix/1, fix_client/1, @@ -86,7 +89,7 @@ make_verify_fun(Module, Function, InitialUserState) -> Module:module_info() catch _:Exception -> - rabbit_log:error("TLS verify_fun: module ~ts missing: ~tp", + ?LOG_ERROR("TLS verify_fun: module ~ts missing: ~tp", [Module, Exception]), throw({error, {invalid_verify_fun, missing_module}}) end, @@ -109,7 +112,7 @@ make_verify_fun(Module, Function, InitialUserState) -> Module:Function(Args) end; _ -> - rabbit_log:error("TLS verify_fun: no ~ts:~ts/3 exported", + ?LOG_ERROR("TLS verify_fun: no ~ts:~ts/3 exported", [Module, Function]), throw({error, {invalid_verify_fun, function_not_exported}}) end. diff --git a/deps/rabbit_common/src/rabbit_writer.erl b/deps/rabbit_common/src/rabbit_writer.erl index 2f126af58fd0..4cbb58caab32 100644 --- a/deps/rabbit_common/src/rabbit_writer.erl +++ b/deps/rabbit_common/src/rabbit_writer.erl @@ -27,6 +27,7 @@ %% When a socket write fails, writer will exit. -include("rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([start/6, start_link/6, start/7, start_link/7, start/8, start_link/8]). -export([init/1, @@ -264,10 +265,10 @@ handle_message(emit_stats, State = #wstate{reader = ReaderPid}) -> handle_message(ok, State) -> State; handle_message({_Ref, ok} = Msg, State) -> - rabbit_log:warning("AMQP 0-9-1 channel writer has received a message it does not support: ~p", [Msg]), + ?LOG_WARNING("AMQP 0-9-1 channel writer has received a message it does not support: ~p", [Msg]), State; handle_message({ok, _Ref} = Msg, State) -> - rabbit_log:warning("AMQP 0-9-1 channel writer has received a message it does not support: ~p", [Msg]), + ?LOG_WARNING("AMQP 0-9-1 channel writer has received a message it does not support: ~p", [Msg]), State; handle_message(Message, _State) -> exit({writer, message_not_understood, Message}). diff --git a/deps/rabbit_common/src/worker_pool_sup.erl b/deps/rabbit_common/src/worker_pool_sup.erl index f4c082d86288..aa1d7a5f8fca 100644 --- a/deps/rabbit_common/src/worker_pool_sup.erl +++ b/deps/rabbit_common/src/worker_pool_sup.erl @@ -7,6 +7,9 @@ -module(worker_pool_sup). +-include_lib("kernel/include/logger.hrl"). + + -behaviour(supervisor). -export([start_link/0, start_link/1, start_link/2]). @@ -29,11 +32,11 @@ start_link() -> start_link(Size). start_link(PoolSize) -> - rabbit_log:info("Will use ~tp processes for default worker pool", [PoolSize]), + ?LOG_INFO("Will use ~tp processes for default worker pool", [PoolSize]), start_link(PoolSize, worker_pool:default_pool()). start_link(PoolSize, PoolName) -> - rabbit_log:info("Starting worker pool '~tp' with ~tp processes in it", [PoolName, PoolSize]), + ?LOG_INFO("Starting worker pool '~tp' with ~tp processes in it", [PoolName, PoolSize]), SupName = list_to_atom(atom_to_list(PoolName) ++ "_sup"), supervisor:start_link({local, SupName}, ?MODULE, [PoolSize, PoolName]). diff --git a/deps/rabbitmq_auth_backend_cache/src/rabbit_auth_backend_cache.erl b/deps/rabbitmq_auth_backend_cache/src/rabbit_auth_backend_cache.erl index df5dee4ac9d0..a952ccb0470f 100644 --- a/deps/rabbitmq_auth_backend_cache/src/rabbit_auth_backend_cache.erl +++ b/deps/rabbitmq_auth_backend_cache/src/rabbit_auth_backend_cache.erl @@ -7,6 +7,7 @@ -module(rabbit_auth_backend_cache). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(rabbit_authn_backend). -behaviour(rabbit_authz_backend). @@ -68,13 +69,13 @@ expiry_timestamp(_) -> never. clear_cache_cluster_wide() -> Nodes = rabbit_nodes:list_running(), - rabbit_log:warning("Clearing auth_backend_cache in all nodes : ~p", [Nodes]), + ?LOG_WARNING("Clearing auth_backend_cache in all nodes : ~p", [Nodes]), rabbit_misc:append_rpc_all_nodes(Nodes, ?MODULE, clear_cache, []). clear_cache() -> {ok, AuthCache} = application:get_env(rabbitmq_auth_backend_cache, cache_module), - rabbit_log:warning("Clearing auth_backend_cache"), + ?LOG_WARNING("Clearing auth_backend_cache"), AuthCache:clear(). with_cache(BackendType, {F, A}, Fun) -> @@ -117,4 +118,4 @@ should_cache(Result, Fun) -> _ -> false end. - \ No newline at end of file + diff --git a/deps/rabbitmq_auth_backend_http/src/rabbit_auth_backend_http.erl b/deps/rabbitmq_auth_backend_http/src/rabbit_auth_backend_http.erl index 3a7556177e12..4b5d0c9ad648 100644 --- a/deps/rabbitmq_auth_backend_http/src/rabbit_auth_backend_http.erl +++ b/deps/rabbitmq_auth_backend_http/src/rabbit_auth_backend_http.erl @@ -8,6 +8,7 @@ -module(rabbit_auth_backend_http). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(rabbit_authn_backend). -behaviour(rabbit_authz_backend). @@ -180,10 +181,10 @@ do_http_req(Path0, Query) -> Request = case rabbit_data_coercion:to_atom(Method) of get -> Path = Path0 ++ "?" ++ Query, - rabbit_log:debug("auth_backend_http: GET ~ts", [Path]), + ?LOG_DEBUG("auth_backend_http: GET ~ts", [Path]), {Path, [{"Host", HostHdr}]}; post -> - rabbit_log:debug("auth_backend_http: POST ~ts", [Path0]), + ?LOG_DEBUG("auth_backend_http: POST ~ts", [Path0]), {Path0, [{"Host", HostHdr}], "application/x-www-form-urlencoded", Query} end, RequestTimeout = @@ -196,12 +197,12 @@ do_http_req(Path0, Query) -> {ok, Val2} -> Val2; _ -> RequestTimeout end, - rabbit_log:debug("auth_backend_http: request timeout: ~tp, connection timeout: ~tp", [RequestTimeout, ConnectionTimeout]), + ?LOG_DEBUG("auth_backend_http: request timeout: ~tp, connection timeout: ~tp", [RequestTimeout, ConnectionTimeout]), HttpOpts = [{timeout, RequestTimeout}, {connect_timeout, ConnectionTimeout}] ++ ssl_options(), case httpc:request(Method, Request, HttpOpts, []) of {ok, {{_HTTP, Code, _}, _Headers, Body}} -> - rabbit_log:debug("auth_backend_http: response code is ~tp, body: ~tp", [Code, Body]), + ?LOG_DEBUG("auth_backend_http: response code is ~tp, body: ~tp", [Code, Body]), case lists:member(Code, ?SUCCESSFUL_RESPONSE_CODES) of true -> parse_resp(Body); false -> {error, {Code, Body}} @@ -216,7 +217,7 @@ ssl_options() -> Opts1 = [{ssl, rabbit_ssl_options:fix_client(Opts0)}], case application:get_env(rabbitmq_auth_backend_http, ssl_hostname_verification) of {ok, wildcard} -> - rabbit_log:debug("Enabling wildcard-aware hostname verification for HTTP client connections"), + ?LOG_DEBUG("Enabling wildcard-aware hostname verification for HTTP client connections"), %% Needed for HTTPS connections that connect to servers that use wildcard certificates. %% See https://erlang.org/doc/man/public_key.html#pkix_verify_hostname_match_fun-1. [{customize_hostname_check, [{match_fun, public_key:pkix_verify_hostname_match_fun(https)}]} | Opts1]; diff --git a/deps/rabbitmq_auth_backend_oauth2/src/rabbit_auth_backend_oauth2.erl b/deps/rabbitmq_auth_backend_oauth2/src/rabbit_auth_backend_oauth2.erl index 69a6a0f2f923..1cbaadbb086f 100644 --- a/deps/rabbitmq_auth_backend_oauth2/src/rabbit_auth_backend_oauth2.erl +++ b/deps/rabbitmq_auth_backend_oauth2/src/rabbit_auth_backend_oauth2.erl @@ -9,6 +9,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include("oauth2.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(rabbit_authn_backend). -behaviour(rabbit_authz_backend). @@ -63,7 +64,7 @@ description() -> user_login_authentication(Username, AuthProps) -> case authenticate(Username, AuthProps) of {refused, Msg, Args} = AuthResult -> - rabbit_log:debug(Msg, Args), + ?LOG_DEBUG(Msg, Args), AuthResult; _ = AuthResult -> AuthResult @@ -179,7 +180,7 @@ with_decoded_token(DecodedToken, Fun) -> case validate_token_expiry(DecodedToken) of ok -> Fun(DecodedToken); {error, Msg} = Err -> - rabbit_log:error(Msg), + ?LOG_ERROR(Msg), Err end. @@ -418,7 +419,7 @@ username_from(PreferredUsernameClaims, DecodedToken) -> [ _One ] -> _One; [ _One | _ ] -> _One end, - rabbit_log:debug("Computing username from client's JWT token: ~ts -> ~ts ", + ?LOG_DEBUG("Computing username from client's JWT token: ~ts -> ~ts ", [lists:flatten(io_lib:format("~p",[ResolvedUsernameClaims])), Username]), Username. diff --git a/deps/rabbitmq_auth_backend_oauth2/src/rabbit_oauth2_provider.erl b/deps/rabbitmq_auth_backend_oauth2/src/rabbit_oauth2_provider.erl index b0346bba1ef9..0ac4c7c46dda 100644 --- a/deps/rabbitmq_auth_backend_oauth2/src/rabbit_oauth2_provider.erl +++ b/deps/rabbitmq_auth_backend_oauth2/src/rabbit_oauth2_provider.erl @@ -8,6 +8,7 @@ -module(rabbit_oauth2_provider). -include("oauth2.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([ get_internal_oauth_provider/0, get_internal_oauth_provider/1, @@ -101,7 +102,7 @@ do_replace_signing_keys(SigningKeys, root) -> proplists:get_value(signing_keys, KeyConfig1, #{}), SigningKeys)} | KeyConfig1], set_env(key_config, KeyConfig2), - rabbit_log:debug("Replacing signing keys for key_config with ~p keys", + ?LOG_DEBUG("Replacing signing keys for key_config with ~p keys", [maps:size(SigningKeys)]), SigningKeys; @@ -115,7 +116,7 @@ do_replace_signing_keys(SigningKeys, OauthProviderId) -> OauthProviders = maps:put(OauthProviderId, OauthProvider, OauthProviders0), set_env(oauth_providers, OauthProviders), - rabbit_log:debug("Replacing signing keys for ~p -> ~p with ~p keys", + ?LOG_DEBUG("Replacing signing keys for ~p -> ~p with ~p keys", [OauthProviderId, OauthProvider, maps:size(SigningKeys)]), SigningKeys. diff --git a/deps/rabbitmq_auth_backend_oauth2/src/uaa_jwt.erl b/deps/rabbitmq_auth_backend_oauth2/src/uaa_jwt.erl index a2f3c56b487c..c293b9c347dd 100644 --- a/deps/rabbitmq_auth_backend_oauth2/src/uaa_jwt.erl +++ b/deps/rabbitmq_auth_backend_oauth2/src/uaa_jwt.erl @@ -16,6 +16,7 @@ -include("oauth2.hrl"). -include_lib("jose/include/jose_jwk.hrl"). +-include_lib("kernel/include/logger.hrl"). -import(rabbit_data_coercion, [ to_map/1]). @@ -44,7 +45,7 @@ add_signing_key(KeyId, Type, Value) -> -spec update_jwks_signing_keys(oauth_provider()) -> ok | {error, term()}. update_jwks_signing_keys(#oauth_provider{id = Id, jwks_uri = JwksUrl, ssl_options = SslOptions}) -> - rabbit_log:debug("Downloading signing keys from ~tp (TLS options: ~p)", + ?LOG_DEBUG("Downloading signing keys from ~tp (TLS options: ~p)", [JwksUrl, format_ssl_options(SslOptions)]), case uaa_jwks:get(JwksUrl, SslOptions) of {ok, {_, _, JwksBody}} -> @@ -52,13 +53,13 @@ update_jwks_signing_keys(#oauth_provider{id = Id, jwks_uri = JwksUrl, jose:decode(erlang:iolist_to_binary(JwksBody)), []), Keys = maps:from_list(lists:map(fun(Key) -> {maps:get(<<"kid">>, Key, undefined), {json, Key}} end, KeyList)), - rabbit_log:debug("Downloaded ~p signing keys", [maps:size(Keys)]), + ?LOG_DEBUG("Downloaded ~p signing keys", [maps:size(Keys)]), case replace_signing_keys(Keys, Id) of {error, _} = Err -> Err; _ -> ok end; {error, _} = Err -> - rabbit_log:error("Failed to download signing keys: ~tp", [Err]), + ?LOG_ERROR("Failed to download signing keys: ~tp", [Err]), Err end. @@ -66,7 +67,7 @@ update_jwks_signing_keys(#oauth_provider{id = Id, jwks_uri = JwksUrl, -> {boolean(), map()} | {error, term()}. decode_and_verify(Token, ResourceServer, InternalOAuthProvider) -> OAuthProviderId = InternalOAuthProvider#internal_oauth_provider.id, - rabbit_log:debug("Decoding token for resource_server: ~p using oauth_provider_id: ~p", + ?LOG_DEBUG("Decoding token for resource_server: ~p using oauth_provider_id: ~p", [ResourceServer#resource_server.id, format_oauth_provider_id(OAuthProviderId)]), Result = case uaa_jwt_jwt:get_key_id(Token) of @@ -81,7 +82,7 @@ decode_and_verify(Token, ResourceServer, InternalOAuthProvider) -> case get_jwk(KeyId, InternalOAuthProvider) of {ok, JWK} -> Algorithms = InternalOAuthProvider#internal_oauth_provider.algorithms, - rabbit_log:debug("Verifying signature using signing_key_id : '~tp' and algorithms: ~p", + ?LOG_DEBUG("Verifying signature using signing_key_id : '~tp' and algorithms: ~p", [KeyId, Algorithms]), uaa_jwt_jwt:decode_and_verify(Algorithms, JWK, Token); {error, _} = Err3 -> @@ -118,7 +119,7 @@ get_jwk(KeyId, InternalOAuthProvider, AllowUpdateJwks) -> undefined -> case AllowUpdateJwks of true -> - rabbit_log:debug("Signing key '~tp' not found. Downloading it... ", [KeyId]), + ?LOG_DEBUG("Signing key '~tp' not found. Downloading it... ", [KeyId]), case get_oauth_provider(OAuthProviderId, [jwks_uri]) of {ok, OAuthProvider} -> case update_jwks_signing_keys(OAuthProvider) of @@ -130,15 +131,15 @@ get_jwk(KeyId, InternalOAuthProvider, AllowUpdateJwks) -> Err end; {error, _} = Error -> - rabbit_log:debug("Unable to download signing keys due to ~p", [Error]), + ?LOG_DEBUG("Unable to download signing keys due to ~p", [Error]), Error end; false -> - rabbit_log:debug("Signing key '~tp' not found. Downloading is not allowed", [KeyId]), + ?LOG_DEBUG("Signing key '~tp' not found. Downloading is not allowed", [KeyId]), {error, key_not_found} end; {Type, Value} -> - rabbit_log:debug("Signing key ~p found", [KeyId]), + ?LOG_DEBUG("Signing key ~p found", [KeyId]), case Type of json -> uaa_jwt_jwk:make_jwk(Value); pem -> uaa_jwt_jwk:from_pem(Value); diff --git a/deps/rabbitmq_auth_backend_oauth2/src/wildcard.erl b/deps/rabbitmq_auth_backend_oauth2/src/wildcard.erl index af583fb5c0df..4687109a55f0 100644 --- a/deps/rabbitmq_auth_backend_oauth2/src/wildcard.erl +++ b/deps/rabbitmq_auth_backend_oauth2/src/wildcard.erl @@ -7,6 +7,9 @@ -module(wildcard). +-include_lib("kernel/include/logger.hrl"). + + -export([match/2]). -spec match(Subject :: binary(), Pattern :: binary()) -> boolean(). @@ -52,7 +55,7 @@ parse_pattern(Pattern) -> Parts = binary:split(Pattern, <<"*">>, [global]), try lists:map(fun(Part) -> cow_qs:urldecode(Part) end, Parts) catch Type:Error -> - rabbit_log:warning("Invalid pattern ~tp : ~tp", + ?LOG_WARNING("Invalid pattern ~tp : ~tp", [Pattern, {Type, Error}]), invalid end. diff --git a/deps/rabbitmq_auth_mechanism_ssl/src/rabbit_auth_mechanism_ssl.erl b/deps/rabbitmq_auth_mechanism_ssl/src/rabbit_auth_mechanism_ssl.erl index ee1f7a9aa657..1a0d878bdcdd 100644 --- a/deps/rabbitmq_auth_mechanism_ssl/src/rabbit_auth_mechanism_ssl.erl +++ b/deps/rabbitmq_auth_mechanism_ssl/src/rabbit_auth_mechanism_ssl.erl @@ -13,6 +13,7 @@ -export([description/0, should_offer/1, init/1, handle_response/2]). -include_lib("public_key/include/public_key.hrl"). +-include_lib("kernel/include/logger.hrl"). -rabbit_boot_step({?MODULE, [{description, "external TLS peer verification-based authentication mechanism"}, @@ -52,7 +53,7 @@ init(Sock) -> not_found -> {refused, none, "no name found", []}; Name -> Val = rabbit_data_coercion:to_binary(Name), - rabbit_log:debug("auth mechanism TLS extracted username '~ts' from peer certificate", [Val]), + ?LOG_DEBUG("auth mechanism TLS extracted username '~ts' from peer certificate", [Val]), Val end; {error, no_peercert} -> diff --git a/deps/rabbitmq_aws/src/rabbitmq_aws.erl b/deps/rabbitmq_aws/src/rabbitmq_aws.erl index 444121d76845..04b6993f89c3 100644 --- a/deps/rabbitmq_aws/src/rabbitmq_aws.erl +++ b/deps/rabbitmq_aws/src/rabbitmq_aws.erl @@ -34,6 +34,7 @@ -endif. -include("rabbitmq_aws.hrl"). +-include_lib("kernel/include/logger.hrl"). %%==================================================================== %% exported wrapper functions @@ -83,9 +84,9 @@ refresh_credentials() -> %% @doc Manually refresh the credentials from the environment, filesystem or EC2 Instance Metadata Service. %% @end refresh_credentials(State) -> - rabbit_log:debug("Refreshing AWS credentials..."), + ?LOG_DEBUG("Refreshing AWS credentials..."), {_, NewState} = load_credentials(State), - rabbit_log:debug("AWS credentials have been refreshed"), + ?LOG_DEBUG("AWS credentials have been refreshed"), set_credentials(NewState). @@ -496,15 +497,15 @@ sign_headers(#state{access_key = AccessKey, %% @doc Determine whether or not an Imdsv2Token has expired. %% @end expired_imdsv2_token(undefined) -> - rabbit_log:debug("EC2 IMDSv2 token has not yet been obtained"), + ?LOG_DEBUG("EC2 IMDSv2 token has not yet been obtained"), true; expired_imdsv2_token({_, _, undefined}) -> - rabbit_log:debug("EC2 IMDSv2 token is not available"), + ?LOG_DEBUG("EC2 IMDSv2 token is not available"), true; expired_imdsv2_token({_, _, Expiration}) -> Now = calendar:datetime_to_gregorian_seconds(local_time()), HasExpired = Now >= Expiration, - rabbit_log:debug("EC2 IMDSv2 token has expired: ~tp", [HasExpired]), + ?LOG_DEBUG("EC2 IMDSv2 token has expired: ~tp", [HasExpired]), HasExpired. @@ -526,7 +527,7 @@ ensure_imdsv2_token_valid() -> %% If the credentials are not available or have expired, then refresh them before performing the request. %% @end ensure_credentials_valid() -> - rabbit_log:debug("Making sure AWS credentials are available and still valid"), + ?LOG_DEBUG("Making sure AWS credentials are available and still valid"), {ok, State} = gen_server:call(rabbitmq_aws, get_state), case has_credentials(State) of true -> case expired_credentials(State#state.expiration) of @@ -541,7 +542,7 @@ ensure_credentials_valid() -> %% @doc Invoke an API call to an AWS service. %% @end api_get_request(Service, Path) -> - rabbit_log:debug("Invoking AWS request {Service: ~tp; Path: ~tp}...", [Service, Path]), + ?LOG_DEBUG("Invoking AWS request {Service: ~tp; Path: ~tp}...", [Service, Path]), api_get_request_with_retries(Service, Path, ?MAX_RETRIES, ?LINEAR_BACK_OFF_MILLIS). @@ -549,20 +550,20 @@ api_get_request(Service, Path) -> %% @doc Invoke an API call to an AWS service with retries. %% @end api_get_request_with_retries(_, _, 0, _) -> - rabbit_log:warning("Request to AWS service has failed after ~b retries", [?MAX_RETRIES]), + ?LOG_WARNING("Request to AWS service has failed after ~b retries", [?MAX_RETRIES]), {error, "AWS service is unavailable"}; api_get_request_with_retries(Service, Path, Retries, WaitTimeBetweenRetries) -> ensure_credentials_valid(), case get(Service, Path) of - {ok, {_Headers, Payload}} -> rabbit_log:debug("AWS request: ~ts~nResponse: ~tp", [Path, Payload]), + {ok, {_Headers, Payload}} -> ?LOG_DEBUG("AWS request: ~ts~nResponse: ~tp", [Path, Payload]), {ok, Payload}; {error, {credentials, _}} -> {error, credentials}; - {error, Message, Response} -> rabbit_log:warning("Error occurred: ~ts", [Message]), + {error, Message, Response} -> ?LOG_WARNING("Error occurred: ~ts", [Message]), case Response of - {_, Payload} -> rabbit_log:warning("Failed AWS request: ~ts~nResponse: ~tp", [Path, Payload]); + {_, Payload} -> ?LOG_WARNING("Failed AWS request: ~ts~nResponse: ~tp", [Path, Payload]); _ -> ok end, - rabbit_log:warning("Will retry AWS request, remaining retries: ~b", [Retries]), + ?LOG_WARNING("Will retry AWS request, remaining retries: ~b", [Retries]), timer:sleep(WaitTimeBetweenRetries), api_get_request_with_retries(Service, Path, Retries - 1, WaitTimeBetweenRetries) end. diff --git a/deps/rabbitmq_aws/src/rabbitmq_aws_config.erl b/deps/rabbitmq_aws/src/rabbitmq_aws_config.erl index 3dbd71e61626..b9c722e8f1b8 100644 --- a/deps/rabbitmq_aws/src/rabbitmq_aws_config.erl +++ b/deps/rabbitmq_aws/src/rabbitmq_aws_config.erl @@ -30,6 +30,7 @@ -endif. -include("rabbitmq_aws.hrl"). +-include_lib("kernel/include/logger.hrl"). -spec credentials() -> security_credentials(). %% @doc Return the credentials from environment variables, configuration or the @@ -627,10 +628,10 @@ parse_az_response({ok, {{_, _, _}, _, _}}) -> {error, undefined}. parse_body_response({error, _}) -> {error, undefined}; parse_body_response({ok, {{_, 200, _}, _, Body}}) -> {ok, Body}; parse_body_response({ok, {{_, 401, _}, _, _}}) -> - rabbit_log:error(get_instruction_on_instance_metadata_error("Unauthorized instance metadata service request.")), + ?LOG_ERROR(get_instruction_on_instance_metadata_error("Unauthorized instance metadata service request.")), {error, undefined}; parse_body_response({ok, {{_, 403, _}, _, _}}) -> - rabbit_log:error(get_instruction_on_instance_metadata_error("The request is not allowed or the instance metadata service is turned off.")), + ?LOG_ERROR(get_instruction_on_instance_metadata_error("The request is not allowed or the instance metadata service is turned off.")), {error, undefined}; parse_body_response({ok, {{_, _, _}, _, _}}) -> {error, undefined}. @@ -654,7 +655,7 @@ parse_credentials_response({ok, {{_, 200, _}, _, Body}}) -> %% @doc Wrap httpc:get/4 to simplify Instance Metadata service v2 requests %% @end perform_http_get_instance_metadata(URL) -> - rabbit_log:debug("Querying instance metadata service: ~tp", [URL]), + ?LOG_DEBUG("Querying instance metadata service: ~tp", [URL]), httpc:request(get, {URL, instance_metadata_request_headers()}, [{timeout, ?DEFAULT_HTTP_TIMEOUT}], []). @@ -717,17 +718,17 @@ region_from_availability_zone(Value) -> %% @end load_imdsv2_token() -> TokenUrl = imdsv2_token_url(), - rabbit_log:info("Attempting to obtain EC2 IMDSv2 token from ~tp ...", [TokenUrl]), + ?LOG_INFO("Attempting to obtain EC2 IMDSv2 token from ~tp ...", [TokenUrl]), case httpc:request(put, {TokenUrl, [{?METADATA_TOKEN_TTL_HEADER, integer_to_list(?METADATA_TOKEN_TTL_SECONDS)}]}, [{timeout, ?DEFAULT_HTTP_TIMEOUT}], []) of {ok, {{_, 200, _}, _, Value}} -> - rabbit_log:debug("Successfully obtained EC2 IMDSv2 token."), + ?LOG_DEBUG("Successfully obtained EC2 IMDSv2 token."), Value; {error, {{_, 400, _}, _, _}} -> - rabbit_log:warning("Failed to obtain EC2 IMDSv2 token: Missing or Invalid Parameters – The PUT request is not valid."), + ?LOG_WARNING("Failed to obtain EC2 IMDSv2 token: Missing or Invalid Parameters – The PUT request is not valid."), undefined; Other -> - rabbit_log:warning( + ?LOG_WARNING( get_instruction_on_instance_metadata_error("Failed to obtain EC2 IMDSv2 token: ~tp. " "Falling back to EC2 IMDSv1 for now. It is recommended to use EC2 IMDSv2."), [Other]), undefined @@ -741,7 +742,7 @@ instance_metadata_request_headers() -> case application:get_env(rabbit, aws_prefer_imdsv2) of {ok, false} -> []; _ -> %% undefined or {ok, true} - rabbit_log:debug("EC2 Instance Metadata Service v2 (IMDSv2) is preferred."), + ?LOG_DEBUG("EC2 Instance Metadata Service v2 (IMDSv2) is preferred."), maybe_imdsv2_token_headers() end. diff --git a/deps/rabbitmq_consistent_hash_exchange/src/rabbit_db_ch_exchange.erl b/deps/rabbitmq_consistent_hash_exchange/src/rabbit_db_ch_exchange.erl index 6ffc6d16c8b6..d8187875355a 100644 --- a/deps/rabbitmq_consistent_hash_exchange/src/rabbit_db_ch_exchange.erl +++ b/deps/rabbitmq_consistent_hash_exchange/src/rabbit_db_ch_exchange.erl @@ -9,6 +9,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include_lib("khepri/include/khepri.hrl"). -include("rabbitmq_consistent_hash_exchange.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([ setup_schema/0, @@ -56,7 +57,7 @@ create_in_mnesia_tx(X) -> case mnesia:read(?HASH_RING_STATE_TABLE, X) of [_] -> ok; [] -> - rabbit_log:debug("Consistent hashing exchange: will initialise hashing ring schema database record"), + ?LOG_DEBUG("Consistent hashing exchange: will initialise hashing ring schema database record"), mnesia:write_lock_table(?HASH_RING_STATE_TABLE), ok = mnesia:write(?HASH_RING_STATE_TABLE, #chx_hash_ring{ exchange = X, @@ -184,7 +185,7 @@ delete_bindings_in_mnesia(Bindings, DeleteFun) -> end). delete_binding_in_mnesia(#binding{source = S, destination = D, key = RK}, DeleteFun) -> - rabbit_log:debug("Consistent hashing exchange: removing binding " + ?LOG_DEBUG("Consistent hashing exchange: removing binding " "from exchange ~ts to destination ~ts with routing key '~ts'", [rabbit_misc:rs(S), rabbit_misc:rs(D), RK]), case mnesia:read(?HASH_RING_STATE_TABLE, S) of diff --git a/deps/rabbitmq_consistent_hash_exchange/src/rabbit_exchange_type_consistent_hash.erl b/deps/rabbitmq_consistent_hash_exchange/src/rabbit_exchange_type_consistent_hash.erl index a60b52f3939f..e5a4f755f4f7 100644 --- a/deps/rabbitmq_consistent_hash_exchange/src/rabbit_exchange_type_consistent_hash.erl +++ b/deps/rabbitmq_consistent_hash_exchange/src/rabbit_exchange_type_consistent_hash.erl @@ -9,6 +9,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include("rabbitmq_consistent_hash_exchange.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(rabbit_exchange_type). @@ -72,7 +73,7 @@ route(#exchange{name = Name, SelectedBucket = jump_consistent_hash(K, N), case maps:get(SelectedBucket, BM, undefined) of undefined -> - rabbit_log:warning("Bucket ~tp not found", [SelectedBucket]), + ?LOG_WARNING("Bucket ~tp not found", [SelectedBucket]), []; Queue -> [Queue] @@ -122,11 +123,11 @@ recover() -> %% starting with RabbitMQ 3.8.4 case list_exchanges() of {error, Reason} -> - rabbit_log:error( + ?LOG_ERROR( "Consistent hashing exchange: failed to recover durable exchange ring state, reason: ~tp", [Reason]); Xs -> - rabbit_log:debug("Consistent hashing exchange: have ~b durable exchanges to recover", [length(Xs)]), + ?LOG_DEBUG("Consistent hashing exchange: have ~b durable exchanges to recover", [length(Xs)]), %% TODO we need to know if we're first on the cluster to reset storage. In mnesia it's a ram table [recover_exchange_and_bindings(X) || X <- lists:usort(Xs)] end. @@ -136,14 +137,14 @@ list_exchanges() -> rabbit_db_exchange:match(Pattern). recover_exchange_and_bindings(#exchange{name = XName} = X) -> - rabbit_log:debug("Consistent hashing exchange: will recover exchange ~ts", [rabbit_misc:rs(XName)]), + ?LOG_DEBUG("Consistent hashing exchange: will recover exchange ~ts", [rabbit_misc:rs(XName)]), create(none, X), - rabbit_log:debug("Consistent hashing exchange: recovered exchange ~ts", [rabbit_misc:rs(XName)]), + ?LOG_DEBUG("Consistent hashing exchange: recovered exchange ~ts", [rabbit_misc:rs(XName)]), Bindings = rabbit_binding:list_for_source(XName), - rabbit_log:debug("Consistent hashing exchange: have ~b bindings to recover for exchange ~ts", + ?LOG_DEBUG("Consistent hashing exchange: have ~b bindings to recover for exchange ~ts", [length(Bindings), rabbit_misc:rs(XName)]), [add_binding(none, X, B) || B <- lists:usort(Bindings)], - rabbit_log:debug("Consistent hashing exchange: recovered bindings for exchange ~ts", + ?LOG_DEBUG("Consistent hashing exchange: recovered bindings for exchange ~ts", [rabbit_misc:rs(XName)]). create(_Serial, X) -> @@ -156,17 +157,17 @@ policy_changed(_X1, _X2) -> ok. add_binding(_Serial, _X, #binding{source = S, destination = D, key = K}) -> Weight = rabbit_data_coercion:to_integer(K), - rabbit_log:debug("Consistent hashing exchange: adding binding from " + ?LOG_DEBUG("Consistent hashing exchange: adding binding from " "exchange ~ts to destination ~ts with routing key '~ts'", [rabbit_misc:rs(S), rabbit_misc:rs(D), K]), case rabbit_db_ch_exchange:create_binding(S, D, Weight, fun chx_hash_ring_update_fun/3) of already_exists -> - rabbit_log:debug("Consistent hashing exchange: NOT adding binding from " + ?LOG_DEBUG("Consistent hashing exchange: NOT adding binding from " "exchange ~s to destination ~s with routing key '~s' " "because this binding (possibly with a different " "routing key) already exists", [rabbit_misc:rs(S), rabbit_misc:rs(D), K]); created -> - rabbit_log:debug("Consistent hashing exchange: adding binding from " + ?LOG_DEBUG("Consistent hashing exchange: adding binding from " "exchange ~s to destination ~s with routing key '~s'", [rabbit_misc:rs(S), rabbit_misc:rs(D), K]) end. @@ -190,7 +191,7 @@ chx_hash_ring_update_fun(#chx_hash_ring{bucket_map = BM0, remove_bindings(_Serial, _X, Bindings) -> Ret = rabbit_db_ch_exchange:delete_bindings(Bindings, fun ch_hash_ring_delete_fun/2), - [rabbit_log:warning("Can't remove binding: hash ring state for exchange ~s wasn't found", + [?LOG_WARNING("Can't remove binding: hash ring state for exchange ~s wasn't found", [rabbit_misc:rs(X)]) || {not_found, X} <- Ret], ok. diff --git a/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link.erl b/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link.erl index 951dd67e4d71..fbdcd396681c 100644 --- a/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link.erl +++ b/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link.erl @@ -10,6 +10,7 @@ -include_lib("amqp_client/include/amqp_client.hrl"). -include_lib("rabbitmq_federation_common/include/rabbit_federation.hrl"). -include("rabbit_exchange_federation.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(gen_server2). @@ -205,14 +206,14 @@ terminate(Reason, #state{downstream_connection = DConn, _ = timer:cancel(TRef), rabbit_federation_link_util:ensure_connection_closed(DConn), - rabbit_log:debug("Exchange federation: link is shutting down, resource cleanup mode: ~tp", [Upstream#upstream.resource_cleanup_mode]), + ?LOG_DEBUG("Exchange federation: link is shutting down, resource cleanup mode: ~tp", [Upstream#upstream.resource_cleanup_mode]), case Upstream#upstream.resource_cleanup_mode of never -> ok; _ -> %% This is a normal shutdown and we are allowed to clean up the internally used queue and exchange - rabbit_log:debug("Federated exchange '~ts' link will delete its internal queue '~ts'", [Upstream#upstream.exchange_name, Queue]), + ?LOG_DEBUG("Federated exchange '~ts' link will delete its internal queue '~ts'", [Upstream#upstream.exchange_name, Queue]), delete_upstream_queue(Conn, Queue), - rabbit_log:debug("Federated exchange '~ts' link will delete its upstream exchange", [Upstream#upstream.exchange_name]), + ?LOG_DEBUG("Federated exchange '~ts' link will delete its upstream exchange", [Upstream#upstream.exchange_name]), delete_upstream_exchange(Conn, IntExchange) end, diff --git a/deps/rabbitmq_jms_topic_exchange/src/rabbit_db_jms_exchange.erl b/deps/rabbitmq_jms_topic_exchange/src/rabbit_db_jms_exchange.erl index bc6af14bbef2..47428dfae8a2 100644 --- a/deps/rabbitmq_jms_topic_exchange/src/rabbit_db_jms_exchange.erl +++ b/deps/rabbitmq_jms_topic_exchange/src/rabbit_db_jms_exchange.erl @@ -9,6 +9,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include_lib("khepri/include/khepri.hrl"). -include("rabbit_jms_topic_exchange.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([ setup_schema/0, @@ -39,7 +40,7 @@ setup_schema() -> setup_schema_in_mnesia() -> TableName = ?JMS_TOPIC_TABLE, - rabbit_log:info( + ?LOG_INFO( "Creating table ~ts for JMS topic exchange", [TableName]), _ = try @@ -79,7 +80,7 @@ setup_schema_in_mnesia() -> Error end catch throw:Reason -> - rabbit_log:error( + ?LOG_ERROR( "Failed to create JMS topic exchange table: ~tp", [Reason]) end, diff --git a/deps/rabbitmq_management/src/rabbit_mgmt_app.erl b/deps/rabbitmq_management/src/rabbit_mgmt_app.erl index e6423ce426c5..126240dbc385 100644 --- a/deps/rabbitmq_management/src/rabbit_mgmt_app.erl +++ b/deps/rabbitmq_management/src/rabbit_mgmt_app.erl @@ -15,6 +15,7 @@ -endif. -include_lib("amqp_client/include/amqp_client.hrl"). +-include_lib("kernel/include/logger.hrl"). -define(TCP_CONTEXT, rabbitmq_management_tcp). -define(TLS_CONTEXT, rabbitmq_management_tls). @@ -37,7 +38,7 @@ start(_Type, _StartArgs) -> true -> start(); false -> - rabbit_log:warning("Metrics collection disabled in management agent, " + ?LOG_WARNING("Metrics collection disabled in management agent, " "management only interface started", []), start() end. @@ -87,7 +88,7 @@ get_listeners_config() -> get_tcp_listener()]; {true, true, true} -> %% what is happening? - rabbit_log:warning("Management plugin: TCP, TLS and a legacy (management.listener.*) listener are all configured. " + ?LOG_WARNING("Management plugin: TCP, TLS and a legacy (management.listener.*) listener are all configured. " "Only two listeners at a time are supported. " "Ignoring the legacy listener"), [get_tcp_listener(), @@ -185,9 +186,9 @@ do_ensure_port(Port, Listener) -> {ok, rabbit_misc:plmerge([{port, Port}], Listener)}. log_startup(tcp, Listener) -> - rabbit_log:info("Management plugin: HTTP (non-TLS) listener started on port ~w", [port(Listener)]); + ?LOG_INFO("Management plugin: HTTP (non-TLS) listener started on port ~w", [port(Listener)]); log_startup(tls, Listener) -> - rabbit_log:info("Management plugin: HTTPS listener started on port ~w", [port(Listener)]). + ?LOG_INFO("Management plugin: HTTPS listener started on port ~w", [port(Listener)]). port(Listener) -> diff --git a/deps/rabbitmq_management/src/rabbit_mgmt_db.erl b/deps/rabbitmq_management/src/rabbit_mgmt_db.erl index da10224749b7..890022a1aaba 100644 --- a/deps/rabbitmq_management/src/rabbit_mgmt_db.erl +++ b/deps/rabbitmq_management/src/rabbit_mgmt_db.erl @@ -12,6 +12,7 @@ -include_lib("rabbit_common/include/rabbit_core_metrics.hrl"). -include("rabbit_mgmt.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(gen_server2). @@ -228,7 +229,7 @@ get_overview(User, Ranges) -> init([]) -> {ok, Interval} = application:get_env(rabbit, collect_statistics_interval), - rabbit_log:info("Statistics database started."), + ?LOG_INFO("Statistics database started."), {ok, #state{interval = Interval}, hibernate, {backoff, ?HIBERNATE_AFTER_MIN, ?HIBERNATE_AFTER_MIN, ?DESIRED_HIBERNATE}}. @@ -713,7 +714,7 @@ merge_data(_, D1, D2) -> % we assume if we get here both values a maps maps_merge(fun merge_data/3, D1, D2) catch error:Err -> - rabbit_log:debug("merge_data err ~tp got: ~tp ~tp", [Err, D1, D2]), + ?LOG_DEBUG("merge_data err ~tp got: ~tp ~tp", [Err, D1, D2]), case is_map(D1) of true -> D1; false -> D2 @@ -755,7 +756,7 @@ delegate_invoke(FunOrMFA) -> {Results, Errors} = delegate:invoke(MemberPids, ?DELEGATE_PREFIX, FunOrMFA), case Errors of [] -> ok; - _ -> rabbit_log:warning("Management delegate query returned errors:~n~tp", [Errors]) + _ -> ?LOG_WARNING("Management delegate query returned errors:~n~tp", [Errors]) end, [R || {_, R} <- Results]. diff --git a/deps/rabbitmq_management/src/rabbit_mgmt_util.erl b/deps/rabbitmq_management/src/rabbit_mgmt_util.erl index 88946e6943f8..a639b45220c3 100644 --- a/deps/rabbitmq_management/src/rabbit_mgmt_util.erl +++ b/deps/rabbitmq_management/src/rabbit_mgmt_util.erl @@ -58,6 +58,7 @@ -include("rabbit_mgmt.hrl"). -include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl"). -include_lib("amqp_client/include/amqp_client.hrl"). +-include_lib("kernel/include/logger.hrl"). -define(FRAMING, rabbit_framing_amqp_0_9_1). -define(DEFAULT_PAGE_SIZE, 100). @@ -154,7 +155,7 @@ get_bool_env(Application, Par, Default) -> true -> true; false -> false; Other -> - rabbit_log:warning("Invalid configuration for application ~tp: ~tp set to ~tp", + ?LOG_WARNING("Invalid configuration for application ~tp: ~tp set to ~tp", [Application, Par, Other]), Default end. @@ -384,7 +385,7 @@ augment_resources0(Resources, DefaultSort, BasicColumns, Pagination, ReqData, [SortFun, PageFun]; {true, extended, _} -> Path = cowboy_req:path(ReqData), - rabbit_log:debug("HTTP API: ~s slow query mode requested - extended sort on ~0p", + ?LOG_DEBUG("HTTP API: ~s slow query mode requested - extended sort on ~0p", [Path, Sort]), % pagination with extended sort columns - SLOW! [AugFun, SortFun, PageFun]; @@ -684,7 +685,7 @@ internal_server_error(Reason, ReqData, Context) -> internal_server_error(internal_server_error, Reason, ReqData, Context). internal_server_error(Error, Reason, ReqData, Context) -> - rabbit_log:error("~ts~n~ts", [Error, Reason]), + ?LOG_ERROR("~ts~n~ts", [Error, Reason]), halt_response(500, Error, Reason, ReqData, Context). invalid_pagination(Type,Reason, ReqData, Context) -> @@ -692,7 +693,7 @@ invalid_pagination(Type,Reason, ReqData, Context) -> redirect_to_home(ReqData, Reason, Context) -> Home = cowboy_req:uri(ReqData, #{path => rabbit_mgmt_util:get_path_prefix() ++ "/", qs => Reason}), - rabbit_log:info("redirect_to_home ~ts ~ts", [Reason, iolist_to_binary(Home)]), + ?LOG_INFO("redirect_to_home ~ts ~ts", [Reason, iolist_to_binary(Home)]), ReqData1 = cowboy_req:reply(302, #{<<"Location">> => iolist_to_binary(Home) }, <<>>, ReqData), @@ -756,7 +757,7 @@ do_read_complete_body_with_limit(Req0, Acc, BodySizeLimit) -> with_decode(Keys, ReqData, Context, Fun) -> case read_complete_body(ReqData) of {error, http_body_limit_exceeded, LimitApplied, BytesRead} -> - rabbit_log:warning("HTTP API: request exceeded maximum allowed payload size (limit: ~tp bytes, payload size: ~tp bytes)", [LimitApplied, BytesRead]), + ?LOG_WARNING("HTTP API: request exceeded maximum allowed payload size (limit: ~tp bytes, payload size: ~tp bytes)", [LimitApplied, BytesRead]), bad_request("Exceeded HTTP request body size limit", ReqData, Context); {ok, Body, ReqData1} -> with_decode(Keys, Body, ReqData1, Context, Fun) @@ -835,23 +836,23 @@ direct_request(MethodName, Transformers, Extra, ErrorMsg, ReqData, VHost, User]) of {badrpc, nodedown} -> Msg = io_lib:format("Node ~tp could not be contacted", [Node]), - rabbit_log:warning(ErrorMsg, [Msg]), + ?LOG_WARNING(ErrorMsg, [Msg]), bad_request(list_to_binary(Msg), ReqData1, Context); {badrpc, {'EXIT', #amqp_error{name = not_found, explanation = Explanation}}} -> - rabbit_log:warning(ErrorMsg, [Explanation]), + ?LOG_WARNING(ErrorMsg, [Explanation]), not_found(Explanation, ReqData1, Context); {badrpc, {'EXIT', #amqp_error{name = access_refused, explanation = Explanation}}} -> - rabbit_log:warning(ErrorMsg, [Explanation]), + ?LOG_WARNING(ErrorMsg, [Explanation]), not_authorised(<<"Access refused.">>, ReqData1, Context); {badrpc, {'EXIT', #amqp_error{name = not_allowed, explanation = Explanation}}} -> - rabbit_log:warning(ErrorMsg, [Explanation]), + ?LOG_WARNING(ErrorMsg, [Explanation]), not_authorised(<<"Access refused.">>, ReqData1, Context); {badrpc, {'EXIT', #amqp_error{explanation = Explanation}}} -> - rabbit_log:warning(ErrorMsg, [Explanation]), + ?LOG_WARNING(ErrorMsg, [Explanation]), bad_request(list_to_binary(Explanation), ReqData1, Context); {badrpc, Reason} -> Msg = io_lib:format("~tp", [Reason]), - rabbit_log:warning(ErrorMsg, [Msg]), + ?LOG_WARNING(ErrorMsg, [Msg]), bad_request( list_to_binary( io_lib:format("Request to node ~ts failed with ~tp", @@ -1081,7 +1082,7 @@ list_login_vhosts(User, AuthzData) -> % rabbitmq/rabbitmq-auth-backend-http#100 log_access_control_result(NotOK) -> - rabbit_log:debug("rabbit_access_control:check_vhost_access result: ~tp", [NotOK]). + ?LOG_DEBUG("rabbit_access_control:check_vhost_access result: ~tp", [NotOK]). %% base64:decode throws lots of weird errors. Catch and convert to one %% that will cause a bad_request. diff --git a/deps/rabbitmq_management/src/rabbit_mgmt_wm_bindings.erl b/deps/rabbitmq_management/src/rabbit_mgmt_wm_bindings.erl index 06d7e6d57fce..138f5af9e7cd 100644 --- a/deps/rabbitmq_management/src/rabbit_mgmt_wm_bindings.erl +++ b/deps/rabbitmq_management/src/rabbit_mgmt_wm_bindings.erl @@ -15,6 +15,7 @@ -include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl"). -include_lib("amqp_client/include/amqp_client.hrl"). +-include_lib("kernel/include/logger.hrl"). %% Use a much lower limit for creating bindings over the HTTP API. %% The payload is not meant to be even 50 KiB in size. @@ -104,7 +105,7 @@ accept_content(ReqData0, {_Mode, Context}) -> {{true, Loc}, ReqData, Context2} end; {error, http_body_limit_exceeded, LimitApplied, BytesRead} -> - rabbit_log:warning("HTTP API: binding creation request exceeded maximum allowed payload size (limit: ~tp bytes, payload size: ~tp bytes)", [LimitApplied, BytesRead]), + ?LOG_WARNING("HTTP API: binding creation request exceeded maximum allowed payload size (limit: ~tp bytes, payload size: ~tp bytes)", [LimitApplied, BytesRead]), rabbit_mgmt_util:bad_request("Payload size limit exceeded", ReqData0, Context) end. diff --git a/deps/rabbitmq_management/src/rabbit_mgmt_wm_connection_sessions.erl b/deps/rabbitmq_management/src/rabbit_mgmt_wm_connection_sessions.erl index aea1c7ddcec5..ff0e53d671b6 100644 --- a/deps/rabbitmq_management/src/rabbit_mgmt_wm_connection_sessions.erl +++ b/deps/rabbitmq_management/src/rabbit_mgmt_wm_connection_sessions.erl @@ -13,6 +13,7 @@ -include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). %%-------------------------------------------------------------------- @@ -87,7 +88,7 @@ session_infos(Pids) -> {ok, Infos} -> {true, Infos}; {error, Reason} -> - rabbit_log:warning("failed to get infos for session ~p: ~tp", + ?LOG_WARNING("failed to get infos for session ~p: ~tp", [Pid, Reason]), false end diff --git a/deps/rabbitmq_management/src/rabbit_mgmt_wm_connection_user_name.erl b/deps/rabbitmq_management/src/rabbit_mgmt_wm_connection_user_name.erl index b5c41ca83f5c..06a72acd77e5 100644 --- a/deps/rabbitmq_management/src/rabbit_mgmt_wm_connection_user_name.erl +++ b/deps/rabbitmq_management/src/rabbit_mgmt_wm_connection_user_name.erl @@ -13,6 +13,7 @@ -include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). %%-------------------------------------------------------------------- @@ -70,8 +71,8 @@ close_user_connection(#tracked_connection{name = Name, pid = Pid, username = Use close_user_connection(#tracked_connection{pid = undefined}, _Username, _ReqData) -> ok; close_user_connection(UnexpectedConn, Username, _ReqData) -> - rabbit_log:debug("~tp Username: ~tp", [?MODULE, Username]), - rabbit_log:debug("~tp unexpected connection: ~tp", [?MODULE, UnexpectedConn]), + ?LOG_DEBUG("~tp Username: ~tp", [?MODULE, Username]), + ?LOG_DEBUG("~tp unexpected connection: ~tp", [?MODULE, UnexpectedConn]), ok. force_close_connection(ReqData, Conn, Pid) -> diff --git a/deps/rabbitmq_management/src/rabbit_mgmt_wm_definitions.erl b/deps/rabbitmq_management/src/rabbit_mgmt_wm_definitions.erl index 343c46951d10..ee46475a944d 100644 --- a/deps/rabbitmq_management/src/rabbit_mgmt_wm_definitions.erl +++ b/deps/rabbitmq_management/src/rabbit_mgmt_wm_definitions.erl @@ -17,6 +17,7 @@ -include("rabbit_mgmt.hrl"). -include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl"). -include_lib("amqp_client/include/amqp_client.hrl"). +-include_lib("kernel/include/logger.hrl"). %%-------------------------------------------------------------------- @@ -96,7 +97,7 @@ accept_json(ReqData0, Context) -> BodySizeLimit = application:get_env(rabbitmq_management, max_http_body_size, ?MANAGEMENT_DEFAULT_HTTP_MAX_BODY_SIZE), case rabbit_mgmt_util:read_complete_body_with_limit(ReqData0, BodySizeLimit) of {error, http_body_limit_exceeded, LimitApplied, BytesRead} -> - _ = rabbit_log:warning("HTTP API: uploaded definition file size (~tp) exceeded the maximum request body limit of ~tp bytes. " + _ = ?LOG_WARNING("HTTP API: uploaded definition file size (~tp) exceeded the maximum request body limit of ~tp bytes. " "Use the 'management.http.max_body_size' key in rabbitmq.conf to increase the limit if necessary", [BytesRead, LimitApplied]), rabbit_mgmt_util:bad_request("Exceeded HTTP request body size limit", ReqData0, Context); {ok, Body, ReqData} -> @@ -191,7 +192,7 @@ accept(Body, ReqData, Context = #context{user = #user{username = Username}}) -> _ = disable_idle_timeout(ReqData), case decode(Body) of {error, E} -> - rabbit_log:error("Encountered an error when parsing definitions: ~tp", [E]), + ?LOG_ERROR("Encountered an error when parsing definitions: ~tp", [E]), rabbit_mgmt_util:bad_request(rabbit_data_coercion:to_binary("failed_to_parse_json"), ReqData, Context); {ok, Map} -> @@ -199,7 +200,7 @@ accept(Body, ReqData, Context = #context{user = #user{username = Username}}) -> none -> case apply_defs(Map, Username) of {error, E} -> - rabbit_log:error("Encountered an error when importing definitions: ~tp", [E]), + ?LOG_ERROR("Encountered an error when importing definitions: ~tp", [E]), rabbit_mgmt_util:bad_request(E, ReqData, Context); ok -> {true, ReqData, Context} end; @@ -209,7 +210,7 @@ accept(Body, ReqData, Context = #context{user = #user{username = Username}}) -> VHost when is_binary(VHost) -> case apply_defs(Map, Username, VHost) of {error, E} -> - rabbit_log:error("Encountered an error when importing definitions: ~tp", [E]), + ?LOG_ERROR("Encountered an error when importing definitions: ~tp", [E]), rabbit_mgmt_util:bad_request(E, ReqData, Context); ok -> {true, ReqData, Context} end diff --git a/deps/rabbitmq_management/src/rabbit_mgmt_wm_rebalance_queues.erl b/deps/rabbitmq_management/src/rabbit_mgmt_wm_rebalance_queues.erl index 64e15e1bbde3..a40717499fdf 100644 --- a/deps/rabbitmq_management/src/rabbit_mgmt_wm_rebalance_queues.erl +++ b/deps/rabbitmq_management/src/rabbit_mgmt_wm_rebalance_queues.erl @@ -14,6 +14,7 @@ -include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). %%-------------------------------------------------------------------- @@ -43,7 +44,7 @@ resource_exists(Req, State) -> accept_content(Req, {_Mode, #context{user = #user{username = Username}}}=State) -> try - rabbit_log:info("User '~ts' has initiated a queue rebalance", [Username]), + ?LOG_INFO("User '~ts' has initiated a queue rebalance", [Username]), spawn(fun() -> rabbit_amqqueue:rebalance(all, <<".*">>, <<".*">>) end), diff --git a/deps/rabbitmq_management/src/rabbit_mgmt_wm_vhost.erl b/deps/rabbitmq_management/src/rabbit_mgmt_wm_vhost.erl index cec419c96af2..fd54e6e31411 100644 --- a/deps/rabbitmq_management/src/rabbit_mgmt_wm_vhost.erl +++ b/deps/rabbitmq_management/src/rabbit_mgmt_wm_vhost.erl @@ -17,6 +17,7 @@ -include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -dialyzer({nowarn_function, accept_content/2}). @@ -98,7 +99,7 @@ delete_resource(ReqData, Context = #context{user = #user{username = Username}}) {error, protected_from_deletion} -> Msg = "Refusing to delete virtual host '~ts' because it is protected from deletion", Reason = iolist_to_binary(io_lib:format(Msg, [VHost])), - rabbit_log:error(Msg, [VHost]), + ?LOG_ERROR(Msg, [VHost]), rabbit_mgmt_util:precondition_failed(Reason, ReqData, Context); {error, timeout} -> rabbit_mgmt_util:internal_server_error( diff --git a/deps/rabbitmq_management/src/rabbit_mgmt_wm_vhost_deletion_protection.erl b/deps/rabbitmq_management/src/rabbit_mgmt_wm_vhost_deletion_protection.erl index c391f671ef72..c24633848330 100644 --- a/deps/rabbitmq_management/src/rabbit_mgmt_wm_vhost_deletion_protection.erl +++ b/deps/rabbitmq_management/src/rabbit_mgmt_wm_vhost_deletion_protection.erl @@ -17,6 +17,7 @@ -include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -dialyzer({nowarn_function, accept_content/2}). @@ -45,13 +46,13 @@ accept_content(ReqData, Context) -> {error, {no_such_vhost, _}} -> Msg = "Cannot enable deletion protection of virtual host '~ts' because it does not exist", Reason = iolist_to_binary(io_lib:format(Msg, [Name])), - rabbit_log:error(Msg, [Name]), + ?LOG_ERROR(Msg, [Name]), rabbit_mgmt_util:not_found( Reason, ReqData, Context); {error, E} -> Msg = "Cannot enable deletion protection of virtual host '~ts': ~tp", Reason = iolist_to_binary(io_lib:format(Msg, [Name, E])), - rabbit_log:error(Msg, [Name]), + ?LOG_ERROR(Msg, [Name]), rabbit_mgmt_util:internal_server_error( Reason, ReqData, Context) end. @@ -64,13 +65,13 @@ delete_resource(ReqData, Context) -> {error, {no_such_vhost, _}} -> Msg = "Cannot disable deletion protection of virtual host '~ts' because it does not exist", Reason = iolist_to_binary(io_lib:format(Msg, [Name])), - rabbit_log:error(Msg, [Name]), + ?LOG_ERROR(Msg, [Name]), rabbit_mgmt_util:not_found( Reason, ReqData, Context); {error, E} -> Msg = "Cannot disable deletion protection of virtual host '~ts': ~tp", Reason = iolist_to_binary(io_lib:format(Msg, [Name, E])), - rabbit_log:error(Msg, [Name]), + ?LOG_ERROR(Msg, [Name]), rabbit_mgmt_util:internal_server_error( Reason, ReqData, Context) end. diff --git a/deps/rabbitmq_management_agent/src/rabbit_mgmt_db_handler.erl b/deps/rabbitmq_management_agent/src/rabbit_mgmt_db_handler.erl index ee3d83498abd..4b760306c883 100644 --- a/deps/rabbitmq_management_agent/src/rabbit_mgmt_db_handler.erl +++ b/deps/rabbitmq_management_agent/src/rabbit_mgmt_db_handler.erl @@ -8,6 +8,7 @@ -module(rabbit_mgmt_db_handler). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). %% Make sure our database is hooked in *before* listening on the network or %% recovering queues (i.e. so there can't be any events fired before it starts). @@ -46,7 +47,7 @@ handle_force_fine_statistics() -> undefined -> ok; X -> - rabbit_log:warning( + ?LOG_WARNING( "force_fine_statistics set to ~tp; ignored.~n" "Replaced by {rates_mode, none} in the rabbitmq_management " "application.", [X]) @@ -58,7 +59,7 @@ ensure_statistics_enabled() -> ForceStats = rates_mode() =/= none, handle_force_fine_statistics(), {ok, StatsLevel} = application:get_env(rabbit, collect_statistics), - rabbit_log:info("Management plugin: using rates mode '~tp'", [rates_mode()]), + ?LOG_INFO("Management plugin: using rates mode '~tp'", [rates_mode()]), case {ForceStats, StatsLevel} of {true, fine} -> ok; @@ -105,7 +106,7 @@ code_change(_OldVsn, State, _Extra) -> ensure_statistics_disabled() -> %% Reset the default values, see Makefile - _ = rabbit_log:info("Management plugin: to stop collect_statistics."), + _ = ?LOG_INFO("Management plugin: to stop collect_statistics."), application:set_env(rabbit, collect_statistics, none), application:set_env(rabbit, collect_statistics_interval, 5000), ok = rabbit:force_event_refresh(erlang:make_ref()). diff --git a/deps/rabbitmq_management_agent/src/rabbit_mgmt_external_stats.erl b/deps/rabbitmq_management_agent/src/rabbit_mgmt_external_stats.erl index 881f7e5568ac..6e32fef39e7e 100644 --- a/deps/rabbitmq_management_agent/src/rabbit_mgmt_external_stats.erl +++ b/deps/rabbitmq_management_agent/src/rabbit_mgmt_external_stats.erl @@ -7,6 +7,9 @@ -module(rabbit_mgmt_external_stats). +-include_lib("kernel/include/logger.hrl"). + + -behaviour(gen_server). -export([start_link/0]). @@ -154,7 +157,7 @@ get_disk_free() -> ?SAFE_CALL(rabbit_disk_monitor:get_disk_free(), log_fd_warning_once(Fmt, Args, #state{fd_warning_logged = undefined}=State) -> % no warning has been logged, so log it and make a note of when - ok = rabbit_log:warning(Fmt, Args), + ok = ?LOG_WARNING(Fmt, Args), State#state{fd_warning_logged = true}; log_fd_warning_once(_Fmt, _Args, #state{fd_warning_logged = true}=State) -> State. @@ -163,7 +166,7 @@ log_fd_error(Fmt, Args, #state{error_logged_time = undefined}=State) -> % rabbitmq/rabbitmq-management#90 % no errors have been logged, so log it and make a note of when Now = erlang:monotonic_time(second), - ok = rabbit_log:error(Fmt, Args), + ok = ?LOG_ERROR(Fmt, Args), State#state{error_logged_time = Now}; log_fd_error(Fmt, Args, #state{error_logged_time = Time}=State) -> Now = erlang:monotonic_time(second), @@ -172,7 +175,7 @@ log_fd_error(Fmt, Args, #state{error_logged_time = Time}=State) -> % rabbitmq/rabbitmq-management#90 % it has been longer than 10 minutes, % re-log the error - ok = rabbit_log:error(Fmt, Args), + ok = ?LOG_ERROR(Fmt, Args), State#state{error_logged_time = Now}; _ -> % 10 minutes have not yet passed diff --git a/deps/rabbitmq_management_agent/src/rabbit_mgmt_storage.erl b/deps/rabbitmq_management_agent/src/rabbit_mgmt_storage.erl index a90b1244a4d6..dd0ee6b78967 100644 --- a/deps/rabbitmq_management_agent/src/rabbit_mgmt_storage.erl +++ b/deps/rabbitmq_management_agent/src/rabbit_mgmt_storage.erl @@ -16,13 +16,14 @@ code_change/3]). -include("rabbit_mgmt_metrics.hrl"). +-include_lib("kernel/include/logger.hrl"). %% ETS owner start_link() -> gen_server2:start_link({local, ?MODULE}, ?MODULE, [], []). reset() -> - rabbit_log:warning("Resetting RabbitMQ management storage"), + ?LOG_WARNING("Resetting RabbitMQ management storage"), [ets:delete_all_objects(IndexTable) || IndexTable <- ?INDEX_TABLES], [ets:delete_all_objects(Table) || {Table, _} <- ?TABLES], _ = rabbit_mgmt_metrics_collector:reset_all(), diff --git a/deps/rabbitmq_mqtt/src/rabbit_mqtt_internal_event_handler.erl b/deps/rabbitmq_mqtt/src/rabbit_mqtt_internal_event_handler.erl index 84e7f44db90c..26b230fdd349 100644 --- a/deps/rabbitmq_mqtt/src/rabbit_mqtt_internal_event_handler.erl +++ b/deps/rabbitmq_mqtt/src/rabbit_mqtt_internal_event_handler.erl @@ -7,6 +7,9 @@ -module(rabbit_mqtt_internal_event_handler). +-include_lib("kernel/include/logger.hrl"). + + -behaviour(gen_event). -export([init/1, handle_event/2, handle_call/2, handle_info/2]). @@ -28,7 +31,7 @@ handle_event({event, vhost_deleted, Info, _, _}, ?STATE) -> {ok, ?STATE}; handle_event({event, maintenance_connections_closed, _Info, _, _}, ?STATE) -> {ok, NConnections} = rabbit_mqtt:close_local_client_connections(maintenance), - rabbit_log:warning("Closed ~b local (Web) MQTT client connections", [NConnections]), + ?LOG_WARNING("Closed ~b local (Web) MQTT client connections", [NConnections]), {ok, ?STATE}; handle_event(_Event, ?STATE) -> {ok, ?STATE}. diff --git a/deps/rabbitmq_peer_discovery_aws/src/rabbit_peer_discovery_aws.erl b/deps/rabbitmq_peer_discovery_aws/src/rabbit_peer_discovery_aws.erl index bec7390defad..ad1617aef9a7 100644 --- a/deps/rabbitmq_peer_discovery_aws/src/rabbit_peer_discovery_aws.erl +++ b/deps/rabbitmq_peer_discovery_aws/src/rabbit_peer_discovery_aws.erl @@ -11,6 +11,7 @@ -behaviour(rabbit_peer_discovery_backend). -include_lib("rabbitmq_peer_discovery_common/include/rabbit_peer_discovery.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([init/0, list_nodes/0, supports_registration/0, register/0, unregister/0, post_registration/0, lock/1, unlock/1]). @@ -73,7 +74,7 @@ %% init() -> - rabbit_log:debug("Peer discovery AWS: initialising..."), + ?LOG_DEBUG("Peer discovery AWS: initialising..."), ok = application:ensure_started(inets), %% we cannot start this plugin yet since it depends on the rabbit app, %% which is in the process of being started by the time this function is called @@ -86,14 +87,14 @@ init() -> list_nodes() -> M = ?CONFIG_MODULE:config_map(?BACKEND_CONFIG_KEY), {ok, _} = application:ensure_all_started(rabbitmq_aws), - rabbit_log:debug("Will use AWS access key of '~ts'", [get_config_key(aws_access_key, M)]), + ?LOG_DEBUG("Will use AWS access key of '~ts'", [get_config_key(aws_access_key, M)]), ok = maybe_set_region(get_config_key(aws_ec2_region, M)), ok = maybe_set_credentials(get_config_key(aws_access_key, M), get_config_key(aws_secret_key, M)), case get_config_key(aws_autoscaling, M) of true -> case rabbitmq_aws_config:instance_id() of - {ok, InstanceId} -> rabbit_log:debug("EC2 instance ID is determined from metadata service: ~tp", [InstanceId]), + {ok, InstanceId} -> ?LOG_DEBUG("EC2 instance ID is determined from metadata service: ~tp", [InstanceId]), get_autoscaling_group_node_list(InstanceId, get_tags()); _ -> {error, "Failed to determine EC2 instance ID from metadata service"} end; @@ -127,7 +128,7 @@ lock(Nodes) -> Node = node(), case lists:member(Node, Nodes) of true -> - rabbit_log:info("Will try to lock connecting to nodes ~tp", [Nodes]), + ?LOG_INFO("Will try to lock connecting to nodes ~tp", [Nodes]), LockId = rabbit_nodes:lock_id(Node), Retries = rabbit_nodes:lock_retries(), case global:set_lock(LockId, Nodes, Retries) of @@ -166,7 +167,7 @@ get_config_key(Key, Map) -> maybe_set_credentials("undefined", _) -> ok; maybe_set_credentials(_, "undefined") -> ok; maybe_set_credentials(AccessKey, SecretKey) -> - rabbit_log:debug("Setting AWS credentials, access key: '~ts'", [AccessKey]), + ?LOG_DEBUG("Setting AWS credentials, access key: '~ts'", [AccessKey]), rabbitmq_aws:set_credentials(AccessKey, SecretKey). @@ -180,7 +181,7 @@ maybe_set_region("undefined") -> {ok, Region} -> maybe_set_region(Region) end; maybe_set_region(Value) -> - rabbit_log:debug("Setting AWS region to ~tp", [Value]), + ?LOG_DEBUG("Setting AWS region to ~tp", [Value]), rabbitmq_aws:set_region(Value). get_autoscaling_group_node_list(Instance, Tag) -> @@ -188,20 +189,20 @@ get_autoscaling_group_node_list(Instance, Tag) -> {ok, Instances} -> case find_autoscaling_group(Instances, Instance) of {ok, Group} -> - rabbit_log:debug("Performing autoscaling group discovery, group: ~tp", [Group]), + ?LOG_DEBUG("Performing autoscaling group discovery, group: ~tp", [Group]), Values = get_autoscaling_instances(Instances, Group, []), - rabbit_log:debug("Performing autoscaling group discovery, found instances: ~tp", [Values]), + ?LOG_DEBUG("Performing autoscaling group discovery, found instances: ~tp", [Values]), case get_hostname_by_instance_ids(Values, Tag) of error -> Msg = "Cannot discover any nodes: DescribeInstances API call failed", - rabbit_log:error(Msg), + ?LOG_ERROR(Msg), {error, Msg}; Names -> - rabbit_log:debug("Performing autoscaling group-based discovery, hostnames: ~tp", [Names]), + ?LOG_DEBUG("Performing autoscaling group-based discovery, hostnames: ~tp", [Names]), {ok, {[?UTIL_MODULE:node_name(N) || N <- Names], disc}} end; error -> - rabbit_log:warning("Cannot discover any nodes because no AWS " + ?LOG_WARNING("Cannot discover any nodes because no AWS " "autoscaling group could be found in " "the instance description. Make sure that this instance" " belongs to an autoscaling group.", []), @@ -209,7 +210,7 @@ get_autoscaling_group_node_list(Instance, Tag) -> end; _ -> Msg = "Cannot discover any nodes because AWS autoscaling group description API call failed", - rabbit_log:warning(Msg), + ?LOG_WARNING(Msg), {error, Msg} end. @@ -242,7 +243,7 @@ fetch_all_autoscaling_instances(QArgs, Accum) -> NextToken = get_next_token(Payload), get_all_autoscaling_instances(lists:append(Instances, Accum), NextToken); {error, Reason} = Error -> - rabbit_log:error("Error fetching autoscaling group instance list: ~tp", [Reason]), + ?LOG_ERROR("Error fetching autoscaling group instance list: ~tp", [Reason]), Error end. @@ -307,7 +308,7 @@ maybe_add_tag_filters(Tags, QArgs, Num) -> -spec get_node_list_from_tags(tags()) -> {ok, {[node()], disc}}. get_node_list_from_tags(M) when map_size(M) =:= 0 -> - rabbit_log:warning("Cannot discover any nodes because AWS tags are not configured!", []), + ?LOG_WARNING("Cannot discover any nodes because AWS tags are not configured!", []), {ok, {[], disc}}; get_node_list_from_tags(Tags) -> {ok, {[?UTIL_MODULE:node_name(N) || N <- get_hostname_by_tags(Tags)], disc}}. @@ -329,7 +330,7 @@ get_hostname_names(Path) -> ReservationSet = proplists:get_value("reservationSet", Response), get_hostname_name_from_reservation_set(ReservationSet, []); {error, Reason} -> - rabbit_log:error("Error fetching node list via EC2 API, request path: ~ts, error: ~tp", [Path, Reason]), + ?LOG_ERROR("Error fetching node list via EC2 API, request path: ~ts, error: ~tp", [Path, Reason]), error end. @@ -339,7 +340,7 @@ get_hostname_by_tags(Tags) -> Path = "/?" ++ rabbitmq_aws_urilib:build_query_string(QArgs2), case get_hostname_names(Path) of error -> - rabbit_log:warning("Cannot discover any nodes because AWS " + ?LOG_WARNING("Cannot discover any nodes because AWS " "instance description with tags ~tp failed", [Tags]), []; Names -> diff --git a/deps/rabbitmq_peer_discovery_consul/src/rabbitmq_peer_discovery_consul_health_check_helper.erl b/deps/rabbitmq_peer_discovery_consul/src/rabbitmq_peer_discovery_consul_health_check_helper.erl index 8d832c514e38..7dc62dc26d22 100644 --- a/deps/rabbitmq_peer_discovery_consul/src/rabbitmq_peer_discovery_consul_health_check_helper.erl +++ b/deps/rabbitmq_peer_discovery_consul/src/rabbitmq_peer_discovery_consul_health_check_helper.erl @@ -17,6 +17,7 @@ -include_lib("rabbitmq_peer_discovery_common/include/rabbit_peer_discovery.hrl"). -include("rabbit_peer_discovery_consul.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, @@ -93,7 +94,7 @@ set_up_periodic_health_check() -> %% notifications IntervalInMs = Interval * 500, % note this is 1/2 - rabbit_log:info("Starting Consul health check notifier (effective interval: ~tp milliseconds)", [IntervalInMs]), + ?LOG_INFO("Starting Consul health check notifier (effective interval: ~tp milliseconds)", [IntervalInMs]), {ok, TRef} = timer:apply_interval(IntervalInMs, rabbit_peer_discovery_consul, send_health_check_pass, []), {ok, #state{timer_ref = TRef}} diff --git a/deps/rabbitmq_peer_discovery_etcd/src/rabbit_peer_discovery_etcd.erl b/deps/rabbitmq_peer_discovery_etcd/src/rabbit_peer_discovery_etcd.erl index 6ce7fdbf5e02..a876ebdcc1b3 100644 --- a/deps/rabbitmq_peer_discovery_etcd/src/rabbit_peer_discovery_etcd.erl +++ b/deps/rabbitmq_peer_discovery_etcd/src/rabbit_peer_discovery_etcd.erl @@ -12,6 +12,7 @@ -include_lib("rabbitmq_peer_discovery_common/include/rabbit_peer_discovery.hrl"). -include("rabbit_peer_discovery_etcd.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([init/0, list_nodes/0, supports_registration/0, register/0, unregister/0, post_registration/0, lock/1, unlock/1]). @@ -32,14 +33,14 @@ init() -> %% We need to do it conditionally, however. NoOp = fun() -> ok end, Run = fun(_) -> - rabbit_log:debug("Peer discovery etcd: initialising..."), + ?LOG_DEBUG("Peer discovery etcd: initialising..."), _ = application:ensure_all_started(eetcd), Formation = application:get_env(rabbit, cluster_formation, []), Opts = maps:from_list(proplists:get_value(peer_discovery_etcd, Formation, [])), {ok, Pid} = rabbitmq_peer_discovery_etcd_v3_client:start_link(Opts), %% unlink so that this supervisor's lifecycle does not affect RabbitMQ core unlink(Pid), - rabbit_log:debug("etcd peer discovery: v3 client pid: ~tp", [whereis(rabbitmq_peer_discovery_etcd_v3_client)]) + ?LOG_DEBUG("etcd peer discovery: v3 client pid: ~tp", [whereis(rabbitmq_peer_discovery_etcd_v3_client)]) end, rabbit_peer_discovery_util:maybe_backend_configured(?BACKEND_CONFIG_KEY, NoOp, NoOp, Run), @@ -51,7 +52,7 @@ init() -> list_nodes() -> Fun0 = fun() -> {ok, {[], disc}} end, Fun1 = fun() -> - rabbit_log:warning("Peer discovery backend is set to ~ts " + ?LOG_WARNING("Peer discovery backend is set to ~ts " "but final config does not contain " "rabbit.cluster_formation.peer_discovery_etcd. " "Cannot discover any nodes because etcd cluster details are not configured!", @@ -80,7 +81,7 @@ supports_registration() -> register() -> Result = ?ETCD_CLIENT:register(), - rabbit_log:info("Registered node with etcd"), + ?LOG_INFO("Registered node with etcd"), Result. diff --git a/deps/rabbitmq_peer_discovery_etcd/src/rabbitmq_peer_discovery_etcd_v3_client.erl b/deps/rabbitmq_peer_discovery_etcd/src/rabbitmq_peer_discovery_etcd_v3_client.erl index 2b42de2caadf..fdcb0979d58e 100644 --- a/deps/rabbitmq_peer_discovery_etcd/src/rabbitmq_peer_discovery_etcd_v3_client.erl +++ b/deps/rabbitmq_peer_discovery_etcd/src/rabbitmq_peer_discovery_etcd_v3_client.erl @@ -27,6 +27,7 @@ -compile(nowarn_unused_function). -include("rabbit_peer_discovery_etcd.hrl"). +-include_lib("kernel/include/logger.hrl"). %% %% API @@ -85,11 +86,11 @@ init(Args) -> callback_mode() -> [state_functions, state_enter]. terminate(Reason, State, Data) -> - rabbit_log:debug("etcd v3 API client will terminate in state ~tp, reason: ~tp", + ?LOG_DEBUG("etcd v3 API client will terminate in state ~tp, reason: ~tp", [State, Reason]), _ = disconnect(?ETCD_CONN_NAME, Data), - rabbit_log:debug("etcd v3 API client has disconnected"), - rabbit_log:debug("etcd v3 API client: total number of connections to etcd is ~tp", [length(eetcd_conn_sup:info())]), + ?LOG_DEBUG("etcd v3 API client has disconnected"), + ?LOG_DEBUG("etcd v3 API client: total number of connections to etcd is ~tp", [length(eetcd_conn_sup:info())]), ok. register() -> @@ -133,74 +134,74 @@ unlock(ServerRef, LockKey) -> %% recover(enter, _PrevState, #statem_data{endpoints = Endpoints}) -> - rabbit_log:debug("etcd v3 API client has entered recovery state, endpoints: ~ts", + ?LOG_DEBUG("etcd v3 API client has entered recovery state, endpoints: ~ts", [string:join(Endpoints, ",")]), keep_state_and_data; recover(internal, start, Data = #statem_data{endpoints = Endpoints, connection_monitor = Ref}) -> - rabbit_log:debug("etcd v3 API client will attempt to connect, endpoints: ~ts", + ?LOG_DEBUG("etcd v3 API client will attempt to connect, endpoints: ~ts", [string:join(Endpoints, ",")]), maybe_demonitor(Ref), case connect(?ETCD_CONN_NAME, Endpoints, Data) of {ok, Pid} -> - rabbit_log:debug("etcd v3 API client connection: ~tp", [Pid]), - rabbit_log:debug("etcd v3 API client: total number of connections to etcd is ~tp", [length(eetcd_conn_sup:info())]), + ?LOG_DEBUG("etcd v3 API client connection: ~tp", [Pid]), + ?LOG_DEBUG("etcd v3 API client: total number of connections to etcd is ~tp", [length(eetcd_conn_sup:info())]), {next_state, connected, Data#statem_data{ connection_name = ?ETCD_CONN_NAME, connection_pid = Pid, connection_monitor = monitor(process, Pid) }}; {error, Errors} -> - [rabbit_log:error("etcd peer discovery: failed to connect to endpoint ~tp: ~tp", [Endpoint, Err]) || {Endpoint, Err} <- Errors], + [?LOG_ERROR("etcd peer discovery: failed to connect to endpoint ~tp: ~tp", [Endpoint, Err]) || {Endpoint, Err} <- Errors], _ = ensure_disconnected(?ETCD_CONN_NAME, Data), Actions = [{state_timeout, reconnection_interval(), recover}], {keep_state, reset_statem_data(Data), Actions} end; recover(state_timeout, _PrevState, Data) -> - rabbit_log:debug("etcd peer discovery: connection entered a reconnection delay state"), + ?LOG_DEBUG("etcd peer discovery: connection entered a reconnection delay state"), _ = ensure_disconnected(?ETCD_CONN_NAME, Data), {next_state, recover, reset_statem_data(Data)}; recover({call, From}, Req, _Data) -> - rabbit_log:error("etcd v3 API: client received a call ~tp while not connected, will do nothing", [Req]), + ?LOG_ERROR("etcd v3 API: client received a call ~tp while not connected, will do nothing", [Req]), gen_statem:reply(From, {error, not_connected}), keep_state_and_data. connected(enter, _PrevState, Data) -> - rabbit_log:info("etcd peer discovery: successfully connected to etcd"), + ?LOG_INFO("etcd peer discovery: successfully connected to etcd"), {keep_state, acquire_node_key_lease_grant(Data)}; connected(info, {'DOWN', ConnRef, process, ConnPid, Reason}, Data = #statem_data{ connection_pid = ConnPid, connection_monitor = ConnRef }) -> - rabbit_log:debug("etcd peer discovery: connection to etcd ~tp is down: ~tp", [ConnPid, Reason]), + ?LOG_DEBUG("etcd peer discovery: connection to etcd ~tp is down: ~tp", [ConnPid, Reason]), maybe_demonitor(ConnRef), {next_state, recover, reset_statem_data(Data)}; connected({call, From}, {lock, _Node}, Data = #statem_data{connection_name = Conn, lock_ttl_in_seconds = TTL}) -> case eetcd_lease:grant(eetcd_kv:new(Conn), TTL) of {ok, #{'ID' := LeaseID}} -> Key = lock_key_base(Data), - rabbit_log:debug("etcd peer discovery: granted a lease ~tp for registration lock ~ts with TTL = ~tp", [LeaseID, Key, TTL]), + ?LOG_DEBUG("etcd peer discovery: granted a lease ~tp for registration lock ~ts with TTL = ~tp", [LeaseID, Key, TTL]), case eetcd_lock:lock(lock_context(Conn, Data), Key, LeaseID) of {ok, #{key := GeneratedKey}} -> - rabbit_log:debug("etcd peer discovery: successfully acquired a lock, lock owner key: ~ts", [GeneratedKey]), + ?LOG_DEBUG("etcd peer discovery: successfully acquired a lock, lock owner key: ~ts", [GeneratedKey]), reply_and_retain_state(From, {ok, GeneratedKey}); {error, _} = Error -> - rabbit_log:debug("etcd peer discovery: failed to acquire a lock using key ~ts: ~tp", [Key, Error]), + ?LOG_DEBUG("etcd peer discovery: failed to acquire a lock using key ~ts: ~tp", [Key, Error]), reply_and_retain_state(From, Error) end; {error, _} = Error -> - rabbit_log:debug("etcd peer discovery: failed to get a lease for registration lock: ~tp", [Error]), + ?LOG_DEBUG("etcd peer discovery: failed to get a lease for registration lock: ~tp", [Error]), reply_and_retain_state(From, Error) end; connected({call, From}, {unlock, GeneratedKey}, Data = #statem_data{connection_name = Conn}) -> Ctx = unlock_context(Conn, Data), case eetcd_lock:unlock(Ctx, GeneratedKey) of {ok, _} -> - rabbit_log:debug("etcd peer discovery: successfully released lock, lock owner key: ~ts", [GeneratedKey]), + ?LOG_DEBUG("etcd peer discovery: successfully released lock, lock owner key: ~ts", [GeneratedKey]), reply_and_retain_state(From, ok); {error, _} = Error -> - rabbit_log:debug("etcd peer discovery: failed to release registration lock, lock owner key: ~ts, error ~tp", + ?LOG_DEBUG("etcd peer discovery: failed to release registration lock, lock owner key: ~ts, error ~tp", [GeneratedKey, Error]), reply_and_retain_state(From, Error) end; @@ -209,9 +210,9 @@ connected({call, From}, register, Data = #statem_data{connection_name = Conn}) - Key = node_key(Data), case eetcd_kv:put(Ctx, Key, registration_value(Data)) of {ok, _} -> - rabbit_log:debug("etcd peer discovery: put key ~tp, done with registration", [Key]); + ?LOG_DEBUG("etcd peer discovery: put key ~tp, done with registration", [Key]); {error, Reason} -> - rabbit_log:error("etcd peer discovery: put key ~tp failed: ~p", [Key, Reason]) + ?LOG_ERROR("etcd peer discovery: put key ~tp failed: ~p", [Key, Reason]) end, gen_statem:reply(From, ok), keep_state_and_data; @@ -225,21 +226,21 @@ connected({call, From}, list_keys, Data = #statem_data{connection_name = Conn}) Prefix = node_key_base(Data), C1 = eetcd_kv:new(Conn), C2 = eetcd_kv:with_prefix(eetcd_kv:with_key(C1, Prefix)), - rabbit_log:debug("etcd peer discovery: will use prefix ~ts to query for node keys", [Prefix]), + ?LOG_DEBUG("etcd peer discovery: will use prefix ~ts to query for node keys", [Prefix]), {ok, #{kvs := Result}} = eetcd_kv:get(C2), - rabbit_log:debug("etcd peer discovery returned keys: ~tp", [Result]), + ?LOG_DEBUG("etcd peer discovery returned keys: ~tp", [Result]), Values = [{maps:get(create_revision, M), maps:get(value, M)} || M <- Result], - rabbit_log:debug("etcd peer discovery: listing node keys returned ~b results", + ?LOG_DEBUG("etcd peer discovery: listing node keys returned ~b results", [length(Values)]), ParsedNodes = lists:filtermap(fun extract_node/1, Values), - rabbit_log:info("etcd peer discovery: successfully extracted nodes: ~0tp", + ?LOG_INFO("etcd peer discovery: successfully extracted nodes: ~0tp", [ParsedNodes]), gen_statem:reply(From, lists:usort(ParsedNodes)), keep_state_and_data. disconnected(enter, _PrevState, _Data) -> - rabbit_log:info("etcd peer discovery: successfully disconnected from etcd"), + ?LOG_INFO("etcd peer discovery: successfully disconnected from etcd"), keep_state_and_data. @@ -251,7 +252,7 @@ acquire_node_key_lease_grant(Data = #statem_data{connection_name = Name, node_ke %% acquire a lease for TTL {ok, #{'ID' := LeaseID}} = eetcd_lease:grant(Name, TTL), {ok, KeepalivePid} = eetcd_lease:keep_alive(Name, LeaseID), - rabbit_log:debug("etcd peer discovery: acquired a lease ~tp for node key ~ts with TTL = ~tp", [LeaseID, node_key(Data), TTL]), + ?LOG_DEBUG("etcd peer discovery: acquired a lease ~tp for node key ~ts with TTL = ~tp", [LeaseID, node_key(Data), TTL]), Data#statem_data{ node_key_lease_id = LeaseID, node_lease_keepalive_pid = KeepalivePid @@ -296,7 +297,7 @@ registration_value(#statem_data{node_key_lease_id = LeaseID, node_key_ttl_in_sec extract_node({CreatedRev, Payload}) -> case rabbit_json:try_decode(Payload) of {error, _Error} -> - rabbit_log:error("etcd peer discovery: failed to extract node name from etcd value ~tp", + ?LOG_ERROR("etcd peer discovery: failed to extract node name from etcd value ~tp", [Payload]), false; {ok, Map} -> @@ -329,8 +330,8 @@ connect(Name, Endpoints, Data) -> do_connect(Name, Endpoints, Data = #statem_data{username = Username}) -> Opts = connection_options(Data), case Username of - undefined -> rabbit_log:info("etcd peer discovery: will connect to etcd without authentication (no credentials configured)"); - _ -> rabbit_log:info("etcd peer discovery: will connect to etcd as user '~ts'", [Username]) + undefined -> ?LOG_INFO("etcd peer discovery: will connect to etcd without authentication (no credentials configured)"); + _ -> ?LOG_INFO("etcd peer discovery: will connect to etcd as user '~ts'", [Username]) end, case eetcd:open(Name, Endpoints, Opts) of {ok, Pid} -> {ok, Pid}; @@ -339,9 +340,9 @@ do_connect(Name, Endpoints, Data = #statem_data{username = Username}) -> true -> Errors0; false -> [Errors0] end, - rabbit_log:debug("etcd peer discovery: connection errors: ~tp", + ?LOG_DEBUG("etcd peer discovery: connection errors: ~tp", [Errors]), - rabbit_log:debug("etcd peer discovery: are all connection errors benign?: ~tp", + ?LOG_DEBUG("etcd peer discovery: are all connection errors benign?: ~tp", [lists:all(fun error_is_already_started/1, Errors)]), %% If all errors are already_started we can ignore them. %% eetcd registers connections under a name @@ -369,10 +370,10 @@ unregister(Conn, Data = #statem_data{node_key_lease_id = LeaseID, node_lease_kee Ctx = unregistration_context(Conn, Data), Key = node_key(Data), _ = eetcd_kv:delete(Ctx, Key), - rabbit_log:debug("etcd peer discovery: deleted key ~ts, done with unregistration", [Key]), + ?LOG_DEBUG("etcd peer discovery: deleted key ~ts, done with unregistration", [Key]), _ = eetcd_lease:revoke(Ctx, LeaseID), exit(KAPid, normal), - rabbit_log:debug("etcd peer discovery: revoked a lease ~tp for node key ~ts", [LeaseID, Key]), + ?LOG_DEBUG("etcd peer discovery: revoked a lease ~tp for node key ~ts", [LeaseID, Key]), ok. reply_and_retain_state(From, Value) -> @@ -423,10 +424,10 @@ connection_options(#statem_data{tls_options = TlsOpts, obfuscated_password = Password}) -> Opts0 = case TlsOpts of [] -> - rabbit_log:info("etcd v3 API client is configured to use plain TCP (without TLS)"), + ?LOG_INFO("etcd v3 API client is configured to use plain TCP (without TLS)"), [{transport, tcp}]; _ -> - rabbit_log:info("etcd v3 API client is configured to use TLS"), + ?LOG_INFO("etcd v3 API client is configured to use TLS"), [{transport, tls}, {tls_opts, TlsOpts}] end, diff --git a/deps/rabbitmq_prometheus/src/collectors/prometheus_rabbitmq_alarm_metrics_collector.erl b/deps/rabbitmq_prometheus/src/collectors/prometheus_rabbitmq_alarm_metrics_collector.erl index f8693fdc0f86..284ff73c9fc8 100644 --- a/deps/rabbitmq_prometheus/src/collectors/prometheus_rabbitmq_alarm_metrics_collector.erl +++ b/deps/rabbitmq_prometheus/src/collectors/prometheus_rabbitmq_alarm_metrics_collector.erl @@ -11,6 +11,7 @@ -import(prometheus_model_helpers, [create_mf/4, untyped_metric/1]). -include_lib("prometheus/include/prometheus.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(prometheus_collector). @@ -60,7 +61,7 @@ collect_mf(_Registry, Callback) -> ok catch exit:{timeout, _} -> - rabbit_log:error("alarm_metrics_collector failed to emit metrics: " + ?LOG_ERROR("alarm_metrics_collector failed to emit metrics: " "rabbitm_alarm:get_local_alarms timed out"), %% We are not going to render any alarm metrics here. %% Breaks continuity but at least doesn't crash the diff --git a/deps/rabbitmq_prometheus/src/rabbit_prometheus_app.erl b/deps/rabbitmq_prometheus/src/rabbit_prometheus_app.erl index 4de0b36cb8a1..ce0a1c828ecb 100644 --- a/deps/rabbitmq_prometheus/src/rabbit_prometheus_app.erl +++ b/deps/rabbitmq_prometheus/src/rabbit_prometheus_app.erl @@ -7,6 +7,9 @@ -module(rabbit_prometheus_app). +-include_lib("kernel/include/logger.hrl"). + + -behaviour(application). -export([start/2, stop/1]). @@ -125,9 +128,9 @@ do_ensure_port_and_protocol(Port, Protocol, Listener) -> {ok, maps:to_list(M1)}. log_startup(tcp, Listener) -> - rabbit_log:info("Prometheus metrics: HTTP (non-TLS) listener started on port ~w", [port(Listener)]); + ?LOG_INFO("Prometheus metrics: HTTP (non-TLS) listener started on port ~w", [port(Listener)]); log_startup(tls, Listener) -> - rabbit_log:info("Prometheus metrics: HTTPS listener started on port ~w", [port(Listener)]). + ?LOG_INFO("Prometheus metrics: HTTPS listener started on port ~w", [port(Listener)]). port(Listener) -> diff --git a/deps/rabbitmq_sharding/src/rabbit_sharding_shard.erl b/deps/rabbitmq_sharding/src/rabbit_sharding_shard.erl index 86b81265b04d..f2b8cc0cd506 100644 --- a/deps/rabbitmq_sharding/src/rabbit_sharding_shard.erl +++ b/deps/rabbitmq_sharding/src/rabbit_sharding_shard.erl @@ -8,6 +8,7 @@ -module(rabbit_sharding_shard). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([maybe_shard_exchanges/0, ensure_sharded_queues/1, @@ -90,7 +91,7 @@ declare_queue(XName, Durable, N, Node) -> ok catch _Error:Reason -> - rabbit_log:error("sharding failed to declare queue for exchange ~tp" + ?LOG_ERROR("sharding failed to declare queue for exchange ~tp" " - soft error:~n~tp", [exchange_bin(XName), Reason]), error @@ -119,7 +120,7 @@ binding_action(F, XName, RoutingKey, N, Node, ErrMsg) -> ?SHARDING_USER) of ok -> ok; {error, Reason} -> - rabbit_log:error(ErrMsg, [QBin, exchange_bin(XName), Reason]), + ?LOG_ERROR(ErrMsg, [QBin, exchange_bin(XName), Reason]), error end. diff --git a/deps/rabbitmq_shovel/src/rabbit_amqp091_shovel.erl b/deps/rabbitmq_shovel/src/rabbit_amqp091_shovel.erl index 1740e7aad2a1..53d2cad75ce9 100644 --- a/deps/rabbitmq_shovel/src/rabbit_amqp091_shovel.erl +++ b/deps/rabbitmq_shovel/src/rabbit_amqp091_shovel.erl @@ -13,6 +13,7 @@ -include_lib("amqp_client/include/amqp_client.hrl"). -include("rabbit_shovel.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([ parse/2, @@ -292,7 +293,7 @@ handle_dest(#'basic.nack'{delivery_tag = Seq, multiple = Multiple}, end, Seq, Multiple, State); handle_dest(#'basic.cancel'{}, #{name := Name}) -> - rabbit_log:warning("Shovel ~tp received a 'basic.cancel' from the server", [Name]), + ?LOG_WARNING("Shovel ~tp received a 'basic.cancel' from the server", [Name]), {stop, {shutdown, restart}}; handle_dest({'EXIT', Conn, Reason}, #{dest := #{current := {Conn, _, _}}}) -> @@ -416,12 +417,12 @@ pop_pending(State = #{dest := Dest}) -> end. make_conn_and_chan([], {VHost, Name} = _ShovelName) -> - rabbit_log:error( + ?LOG_ERROR( "Shovel '~ts' in vhost '~ts' has no more URIs to try for connection", [Name, VHost]), erlang:error(failed_to_connect_using_provided_uris); make_conn_and_chan([], ShovelName) -> - rabbit_log:error( + ?LOG_ERROR( "Shovel '~ts' has no more URIs to try for connection", [ShovelName]), erlang:error(failed_to_connect_using_provided_uris); @@ -450,11 +451,11 @@ do_make_conn_and_chan(URIs, ShovelName) -> end. log_connection_failure(Reason, URI, {VHost, Name} = _ShovelName) -> - rabbit_log:error( + ?LOG_ERROR( "Shovel '~ts' in vhost '~ts' failed to connect (URI: ~ts): ~ts", [Name, VHost, amqp_uri:remove_credentials(URI), human_readable_connection_error(Reason)]); log_connection_failure(Reason, URI, ShovelName) -> - rabbit_log:error( + ?LOG_ERROR( "Shovel '~ts' failed to connect (URI: ~ts): ~ts", [ShovelName, amqp_uri:remove_credentials(URI), human_readable_connection_error(Reason)]). diff --git a/deps/rabbitmq_shovel/src/rabbit_shovel_dyn_worker_sup.erl b/deps/rabbitmq_shovel/src/rabbit_shovel_dyn_worker_sup.erl index 42e85c069512..2ee00b2bcf9a 100644 --- a/deps/rabbitmq_shovel/src/rabbit_shovel_dyn_worker_sup.erl +++ b/deps/rabbitmq_shovel/src/rabbit_shovel_dyn_worker_sup.erl @@ -14,6 +14,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include("rabbit_shovel.hrl"). +-include_lib("kernel/include/logger.hrl"). -define(SUPERVISOR, ?MODULE). start_link(Name, Config) -> @@ -37,8 +38,8 @@ init([Name, Config0]) -> Config = rabbit_data_coercion:to_proplist(Config0), Delay = pget(<<"reconnect-delay">>, Config, ?DEFAULT_RECONNECT_DELAY), case Name of - {VHost, ShovelName} -> rabbit_log:debug("Shovel '~ts' in virtual host '~ts' will use reconnection delay of ~tp", [ShovelName, VHost, Delay]); - ShovelName -> rabbit_log:debug("Shovel '~ts' will use reconnection delay of ~ts", [ShovelName, Delay]) + {VHost, ShovelName} -> ?LOG_DEBUG("Shovel '~ts' in virtual host '~ts' will use reconnection delay of ~tp", [ShovelName, VHost, Delay]); + ShovelName -> ?LOG_DEBUG("Shovel '~ts' will use reconnection delay of ~ts", [ShovelName, Delay]) end, Restart = case Delay of N when is_integer(N) andalso N > 0 -> diff --git a/deps/rabbitmq_shovel/src/rabbit_shovel_parameters.erl b/deps/rabbitmq_shovel/src/rabbit_shovel_parameters.erl index d9932c859d6f..b3fe3ef04f88 100644 --- a/deps/rabbitmq_shovel/src/rabbit_shovel_parameters.erl +++ b/deps/rabbitmq_shovel/src/rabbit_shovel_parameters.erl @@ -12,6 +12,7 @@ -include_lib("amqp_client/include/amqp_client.hrl"). -include("rabbit_shovel.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([validate/5, notify/5, notify_clear/4]). -export([register/0, unregister/0, parse/3]). @@ -230,7 +231,7 @@ validate_params_user(#amqp_params_direct{virtual_host = VHost}, VHostAccess = case catch rabbit_access_control:check_vhost_access(User, VHost, undefined, #{}) of ok -> ok; NotOK -> - rabbit_log:debug("rabbit_access_control:check_vhost_access result: ~tp", [NotOK]), + ?LOG_DEBUG("rabbit_access_control:check_vhost_access result: ~tp", [NotOK]), NotOK end, case rabbit_vhost:exists(VHost) andalso VHostAccess of diff --git a/deps/rabbitmq_shovel/src/rabbit_shovel_util.erl b/deps/rabbitmq_shovel/src/rabbit_shovel_util.erl index 42993700f7af..2b3cc0ff1ab7 100644 --- a/deps/rabbitmq_shovel/src/rabbit_shovel_util.erl +++ b/deps/rabbitmq_shovel/src/rabbit_shovel_util.erl @@ -15,6 +15,7 @@ -include_lib("rabbit_common/include/rabbit_framing.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -define(ROUTING_HEADER, <<"x-shovelled">>). -define(TIMESTAMP_HEADER, <<"x-shovelled-timestamp">>). @@ -42,14 +43,14 @@ delete_shovel(VHost, Name, ActingUser) -> not_found -> %% Follow the user's obvious intent and delete the runtime parameter just in case the Shovel is in %% a starting-failing-restarting loop. MK. - rabbit_log:info("Will delete runtime parameters of shovel '~ts' in virtual host '~ts'", [Name, VHost]), + ?LOG_INFO("Will delete runtime parameters of shovel '~ts' in virtual host '~ts'", [Name, VHost]), ok = rabbit_runtime_parameters:clear(VHost, <<"shovel">>, Name, ActingUser), {error, not_found}; _Obj -> ShovelParameters = rabbit_runtime_parameters:value(VHost, <<"shovel">>, Name), case needs_force_delete(ShovelParameters, ActingUser) of false -> - rabbit_log:info("Will delete runtime parameters of shovel '~ts' in virtual host '~ts'", [Name, VHost]), + ?LOG_INFO("Will delete runtime parameters of shovel '~ts' in virtual host '~ts'", [Name, VHost]), ok = rabbit_runtime_parameters:clear(VHost, <<"shovel">>, Name, ActingUser); true -> report_that_protected_shovel_cannot_be_deleted(Name, VHost, ShovelParameters) diff --git a/deps/rabbitmq_shovel_management/src/rabbit_shovel_mgmt_shovel.erl b/deps/rabbitmq_shovel_management/src/rabbit_shovel_mgmt_shovel.erl index f6a3927bd9aa..044ee556d8b6 100644 --- a/deps/rabbitmq_shovel_management/src/rabbit_shovel_mgmt_shovel.erl +++ b/deps/rabbitmq_shovel_management/src/rabbit_shovel_mgmt_shovel.erl @@ -18,6 +18,7 @@ -include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl"). -include_lib("amqp_client/include/amqp_client.hrl"). -include("rabbit_shovel_mgmt.hrl"). +-include_lib("kernel/include/logger.hrl"). -define(COMPONENT, <<"shovel">>). @@ -47,7 +48,7 @@ resource_exists(ReqData, Context) -> Name -> case get_shovel_node(VHost, Name, ReqData, Context) of undefined -> - rabbit_log:error("Shovel with the name '~ts' was not found on virtual host '~ts'. " + ?LOG_ERROR("Shovel with the name '~ts' was not found on virtual host '~ts'. " "It may be failing to connect and report its status.", [Name, VHost]), case cowboy_req:method(ReqData) of @@ -84,7 +85,7 @@ delete_resource(ReqData, #context{user = #user{username = Username}}=Context) -> {false, ReqData, Context}; Name -> case get_shovel_node(VHost, Name, ReqData, Context) of - undefined -> rabbit_log:error("Could not find shovel data for shovel '~ts' in vhost: '~ts'", [Name, VHost]), + undefined -> ?LOG_ERROR("Could not find shovel data for shovel '~ts' in vhost: '~ts'", [Name, VHost]), case is_restart(ReqData) of true -> {false, ReqData, Context}; @@ -106,14 +107,14 @@ delete_resource(ReqData, #context{user = #user{username = Username}}=Context) -> %% We must distinguish between a delete and a restart case is_restart(ReqData) of true -> - rabbit_log:info("Asked to restart shovel '~ts' in vhost '~ts' on node '~s'", [Name, VHost, Node]), + ?LOG_INFO("Asked to restart shovel '~ts' in vhost '~ts' on node '~s'", [Name, VHost, Node]), try erpc:call(Node, rabbit_shovel_util, restart_shovel, [VHost, Name], ?SHOVEL_CALLS_TIMEOUT_MS) of ok -> {true, ReqData, Context}; {error, not_found} -> - rabbit_log:error("Could not find shovel data for shovel '~s' in vhost: '~s'", [Name, VHost]), + ?LOG_ERROR("Could not find shovel data for shovel '~s' in vhost: '~s'", [Name, VHost]), {false, ReqData, Context} catch _:Reason -> - rabbit_log:error("Failed to restart shovel '~s' on vhost '~s', reason: ~p", + ?LOG_ERROR("Failed to restart shovel '~s' on vhost '~s', reason: ~p", [Name, VHost, Reason]), {false, ReqData, Context} end; @@ -185,20 +186,20 @@ find_matching_shovel(VHost, Name, Shovels) -> -spec try_delete(node(), vhost:name(), any(), rabbit_types:username()) -> true | false | locked | error. try_delete(Node, VHost, Name, Username) -> - rabbit_log:info("Asked to delete shovel '~ts' in vhost '~ts' on node '~s'", [Name, VHost, Node]), + ?LOG_INFO("Asked to delete shovel '~ts' in vhost '~ts' on node '~s'", [Name, VHost, Node]), %% this will clear the runtime parameter, the ultimate way of deleting a dynamic Shovel eventually. MK. try erpc:call(Node, rabbit_shovel_util, delete_shovel, [VHost, Name, Username], ?SHOVEL_CALLS_TIMEOUT_MS) of ok -> true; {error, not_found} -> - rabbit_log:error("Could not find shovel data for shovel '~s' in vhost: '~s'", [Name, VHost]), + ?LOG_ERROR("Could not find shovel data for shovel '~s' in vhost: '~s'", [Name, VHost]), false catch _:{exception, {amqp_error, resource_locked, Reason, _}} -> - rabbit_log:error("Failed to delete shovel '~s' on vhost '~s', reason: ~p", + ?LOG_ERROR("Failed to delete shovel '~s' on vhost '~s', reason: ~p", [Name, VHost, Reason]), locked; _:Reason -> - rabbit_log:error("Failed to delete shovel '~s' on vhost '~s', reason: ~p", + ?LOG_ERROR("Failed to delete shovel '~s' on vhost '~s', reason: ~p", [Name, VHost, Reason]), error end. diff --git a/deps/rabbitmq_stomp/src/rabbit_stomp.erl b/deps/rabbitmq_stomp/src/rabbit_stomp.erl index 570df0f316c4..af7431d9f747 100644 --- a/deps/rabbitmq_stomp/src/rabbit_stomp.erl +++ b/deps/rabbitmq_stomp/src/rabbit_stomp.erl @@ -8,6 +8,7 @@ -module(rabbit_stomp). -include("rabbit_stomp.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(application). -export([start/2, stop/1]). @@ -87,7 +88,7 @@ parse_default_user([{passcode, Passcode} | Rest], Configuration) -> parse_default_user(Rest, Configuration#stomp_configuration{ default_passcode = Passcode}); parse_default_user([Unknown | Rest], Configuration) -> - rabbit_log:warning("rabbit_stomp: ignoring invalid default_user " + ?LOG_WARNING("rabbit_stomp: ignoring invalid default_user " "configuration option: ~tp", [Unknown]), parse_default_user(Rest, Configuration). @@ -97,17 +98,17 @@ report_configuration(#stomp_configuration{ ssl_cert_login = SSLCertLogin}) -> case Login of undefined -> ok; - _ -> rabbit_log:info("rabbit_stomp: default user '~ts' " + _ -> ?LOG_INFO("rabbit_stomp: default user '~ts' " "enabled", [Login]) end, case ImplicitConnect of - true -> rabbit_log:info("rabbit_stomp: implicit connect enabled"); + true -> ?LOG_INFO("rabbit_stomp: implicit connect enabled"); false -> ok end, case SSLCertLogin of - true -> rabbit_log:info("rabbit_stomp: ssl_cert_login enabled"); + true -> ?LOG_INFO("rabbit_stomp: ssl_cert_login enabled"); false -> ok end, diff --git a/deps/rabbitmq_stomp/src/rabbit_stomp_internal_event_handler.erl b/deps/rabbitmq_stomp/src/rabbit_stomp_internal_event_handler.erl index 3073cfe90f9d..4babbc0dd5e8 100644 --- a/deps/rabbitmq_stomp/src/rabbit_stomp_internal_event_handler.erl +++ b/deps/rabbitmq_stomp/src/rabbit_stomp_internal_event_handler.erl @@ -7,6 +7,9 @@ -module(rabbit_stomp_internal_event_handler). +-include_lib("kernel/include/logger.hrl"). + + -behaviour(gen_event). -export([init/1, handle_event/2, handle_call/2, handle_info/2, terminate/2, code_change/3]). @@ -19,7 +22,7 @@ init([]) -> handle_event({event, maintenance_connections_closed, _Info, _, _}, State) -> %% we should close our connections {ok, NConnections} = rabbit_stomp:close_all_client_connections("node is being put into maintenance mode"), - rabbit_log:alert("Closed ~b local STOMP client connections", [NConnections]), + ?LOG_INFO("Closed ~b local STOMP client connections", [NConnections]), {ok, State}; handle_event(_Event, State) -> {ok, State}. diff --git a/deps/rabbitmq_stomp/src/rabbit_stomp_processor.erl b/deps/rabbitmq_stomp/src/rabbit_stomp_processor.erl index aeb694c395eb..84fbea4cfe43 100644 --- a/deps/rabbitmq_stomp/src/rabbit_stomp_processor.erl +++ b/deps/rabbitmq_stomp/src/rabbit_stomp_processor.erl @@ -22,6 +22,7 @@ -include("rabbit_stomp_frame.hrl"). -include("rabbit_stomp.hrl"). -include("rabbit_stomp_headers.hrl"). +-include_lib("kernel/include/logger.hrl"). -record(proc_state, {session_id, channel, connection, subscriptions, version, start_heartbeat_fun, pending_receipts, @@ -610,23 +611,23 @@ do_login(Username, Passwd, VirtualHost, Heartbeat, AdapterInfo, Version, connection = Connection, version = Version}); {error, {auth_failure, _}} -> - rabbit_log:warning("STOMP login failed for user '~ts': authentication failed", [Username]), + ?LOG_WARNING("STOMP login failed for user '~ts': authentication failed", [Username]), error("Bad CONNECT", "Access refused for user '" ++ binary_to_list(Username) ++ "'", [], State); {error, not_allowed} -> - rabbit_log:warning("STOMP login failed for user '~ts': " + ?LOG_WARNING("STOMP login failed for user '~ts': " "virtual host access not allowed", [Username]), error("Bad CONNECT", "Virtual host '" ++ binary_to_list(VirtualHost) ++ "' access denied", State); {error, access_refused} -> - rabbit_log:warning("STOMP login failed for user '~ts': " + ?LOG_WARNING("STOMP login failed for user '~ts': " "virtual host access not allowed", [Username]), error("Bad CONNECT", "Virtual host '" ++ binary_to_list(VirtualHost) ++ "' access denied", State); {error, not_loopback} -> - rabbit_log:warning("STOMP login failed for user '~ts': " + ?LOG_WARNING("STOMP login failed for user '~ts': " "this user's access is restricted to localhost", [Username]), error("Bad CONNECT", "non-loopback access denied", State) end. @@ -898,7 +899,7 @@ close_connection(State = #proc_state{connection = Connection}) -> catch amqp_connection:close(Connection), State#proc_state{channel = none, connection = none, subscriptions = none}; close_connection(undefined) -> - rabbit_log:debug("~ts:close_connection: undefined state", [?MODULE]), + ?LOG_DEBUG("~ts:close_connection: undefined state", [?MODULE]), #proc_state{channel = none, connection = none, subscriptions = none}. %%---------------------------------------------------------------------------- @@ -1194,7 +1195,7 @@ priv_error(Message, Format, Args, ServerPrivateDetail, State) -> State). log_error(Message, Detail, ServerPrivateDetail) -> - rabbit_log:error("STOMP error frame sent:~n" + ?LOG_ERROR("STOMP error frame sent:~n" "Message: ~tp~n" "Detail: ~tp~n" "Server private detail: ~tp", diff --git a/deps/rabbitmq_stream/src/rabbit_stream.erl b/deps/rabbitmq_stream/src/rabbit_stream.erl index e704ce65c55d..5d7547cdf8cc 100644 --- a/deps/rabbitmq_stream/src/rabbit_stream.erl +++ b/deps/rabbitmq_stream/src/rabbit_stream.erl @@ -37,6 +37,7 @@ -include_lib("rabbitmq_stream_common/include/rabbit_stream.hrl"). -include("rabbit_stream_metrics.hrl"). +-include_lib("kernel/include/logger.hrl"). start(_Type, _Args) -> rabbit_stream_metrics:init(), @@ -97,7 +98,7 @@ port_from_listener() -> undefined, Listeners) catch error:Reason -> %% can happen if a remote node calls and the current has not fully started yet - rabbit_log:info("Error while retrieving stream plugin port: ~tp", [Reason]), + ?LOG_INFO("Error while retrieving stream plugin port: ~tp", [Reason]), {error, Reason} end. @@ -123,7 +124,7 @@ tls_port_from_listener() -> undefined, Listeners) catch error:Reason -> %% can happen if a remote node calls and the current has not fully started yet - rabbit_log:info("Error while retrieving stream plugin port: ~tp", [Reason]), + ?LOG_INFO("Error while retrieving stream plugin port: ~tp", [Reason]), {error, Reason} end. diff --git a/deps/rabbitmq_stream/src/rabbit_stream_manager.erl b/deps/rabbitmq_stream/src/rabbit_stream_manager.erl index 7ccb1127c77c..598da4a768ab 100644 --- a/deps/rabbitmq_stream/src/rabbit_stream_manager.erl +++ b/deps/rabbitmq_stream/src/rabbit_stream_manager.erl @@ -22,6 +22,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include_lib("rabbit/include/amqqueue.hrl"). -include_lib("rabbitmq_stream/src/rabbit_stream_utils.hrl"). +-include_lib("kernel/include/logger.hrl"). %% API -export([create/4, @@ -61,26 +62,26 @@ delete(VirtualHost, Reference, Username) -> #resource{virtual_host = VirtualHost, kind = queue, name = Reference}, - rabbit_log:debug("Trying to delete stream ~tp", [Reference]), + ?LOG_DEBUG("Trying to delete stream ~tp", [Reference]), case rabbit_amqqueue:lookup(Name) of {ok, Q} -> - rabbit_log:debug("Found queue record ~tp, checking if it is a stream", + ?LOG_DEBUG("Found queue record ~tp, checking if it is a stream", [Reference]), case is_stream_queue(Q) of true -> - rabbit_log:debug("Queue record ~tp is a stream, trying to delete it", + ?LOG_DEBUG("Queue record ~tp is a stream, trying to delete it", [Reference]), {ok, _} = rabbit_stream_queue:delete(Q, false, false, Username), - rabbit_log:debug("Stream ~tp deleted", [Reference]), + ?LOG_DEBUG("Stream ~tp deleted", [Reference]), {ok, deleted}; _ -> - rabbit_log:debug("Queue record ~tp is NOT a stream, returning error", + ?LOG_DEBUG("Queue record ~tp is NOT a stream, returning error", [Reference]), {error, reference_not_found} end; {error, not_found} -> - rabbit_log:debug("Stream ~tp not found, cannot delete it", + ?LOG_DEBUG("Stream ~tp not found, cannot delete it", [Reference]), {error, reference_not_found} end. @@ -171,7 +172,7 @@ delete_super_stream(VirtualHost, SuperStream, Username) -> ok -> ok; {error, Error} -> - rabbit_log:warning("Error while deleting super stream exchange ~tp, " + ?LOG_WARNING("Error while deleting super stream exchange ~tp, " "~tp", [SuperStream, Error]), ok @@ -181,7 +182,7 @@ delete_super_stream(VirtualHost, SuperStream, Username) -> {ok, deleted} -> ok; {error, Err} -> - rabbit_log:warning("Error while delete partition ~tp of super stream " + ?LOG_WARNING("Error while delete partition ~tp of super stream " "~tp, ~tp", [Stream, SuperStream, Err]), ok @@ -302,7 +303,7 @@ topology(VirtualHost, Stream) -> replica_nodes => []}, Members)}; Err -> - rabbit_log:info("Error locating ~tp stream members: ~tp", + ?LOG_INFO("Error locating ~tp stream members: ~tp", [StreamName, Err]), {error, stream_not_available} end; @@ -333,7 +334,7 @@ route(RoutingKey, VirtualHost, SuperStream) -> end catch exit:Error -> - rabbit_log:warning("Error while looking up exchange ~tp, ~tp", + ?LOG_WARNING("Error while looking up exchange ~tp, ~tp", [rabbit_misc:rs(ExchangeName), Error]), {error, stream_not_found} end. @@ -347,7 +348,7 @@ partitions(VirtualHost, SuperStream) -> {ok, integer()} | {error, stream_not_found}. partition_index(VirtualHost, SuperStream, Stream) -> ExchangeName = rabbit_misc:r(VirtualHost, exchange, SuperStream), - rabbit_log:debug("Looking for partition index of stream ~tp in " + ?LOG_DEBUG("Looking for partition index of stream ~tp in " "super stream ~tp (virtual host ~tp)", [Stream, SuperStream, VirtualHost]), try @@ -359,7 +360,7 @@ partition_index(VirtualHost, SuperStream, Stream) -> is_resource_stream_queue(D), Q == Stream], OrderedBindings = rabbit_stream_utils:sort_partitions(UnorderedBindings), - rabbit_log:debug("Bindings: ~tp", [OrderedBindings]), + ?LOG_DEBUG("Bindings: ~tp", [OrderedBindings]), case OrderedBindings of [] -> {error, stream_not_found}; @@ -393,7 +394,7 @@ partition_index(VirtualHost, SuperStream, Stream) -> end catch exit:Error -> - rabbit_log:error("Error while looking up exchange ~tp, ~tp", + ?LOG_ERROR("Error while looking up exchange ~tp, ~tp", [ExchangeName, Error]), {error, stream_not_found} end. @@ -536,12 +537,12 @@ do_create_stream(VirtualHost, Reference, StreamQueueArguments, Username) -> {existing, _} -> {error, reference_already_exists}; {error, Err} -> - rabbit_log:warning("Error while creating ~tp stream, ~tp", + ?LOG_WARNING("Error while creating ~tp stream, ~tp", [Reference, Err]), {error, internal_error}; {error, queue_limit_exceeded, Reason, ReasonArg} -> - rabbit_log:warning("Cannot declare stream ~tp because, " + ?LOG_WARNING("Cannot declare stream ~tp because, " ++ Reason, [Reference] ++ ReasonArg), {error, validation_failed}; @@ -549,19 +550,19 @@ do_create_stream(VirtualHost, Reference, StreamQueueArguments, Username) -> precondition_failed, Msg, Args} -> - rabbit_log:warning("Error while creating ~tp stream, " + ?LOG_WARNING("Error while creating ~tp stream, " ++ Msg, [Reference] ++ Args), {error, validation_failed} end catch exit:Error -> - rabbit_log:error("Error while creating ~tp stream, ~tp", + ?LOG_ERROR("Error while creating ~tp stream, ~tp", [Reference, Error]), {error, internal_error} end; {error, {absent, _, Reason}} -> - rabbit_log:error("Error while creating ~tp stream, ~tp", + ?LOG_ERROR("Error while creating ~tp stream, ~tp", [Reference, Reason]), {error, internal_error} end @@ -570,12 +571,12 @@ do_create_stream(VirtualHost, Reference, StreamQueueArguments, Username) -> case ExitError of % likely a problem of inequivalent args on an existing stream {amqp_error, precondition_failed, M, _} -> - rabbit_log:info("Error while creating ~tp stream, " + ?LOG_INFO("Error while creating ~tp stream, " ++ M, [Reference]), {error, validation_failed}; E -> - rabbit_log:warning("Error while creating ~tp stream, ~tp", + ?LOG_WARNING("Error while creating ~tp stream, ~tp", [Reference, E]), {error, validation_failed} end @@ -603,7 +604,7 @@ super_stream_partitions(VirtualHost, SuperStream) -> [], OrderedBindings)} catch exit:Error -> - rabbit_log:error("Error while looking up exchange ~tp, ~tp", + ?LOG_ERROR("Error while looking up exchange ~tp, ~tp", [ExchangeName, Error]), {error, stream_not_found} end. @@ -732,7 +733,7 @@ declare_super_stream_exchange(VirtualHost, Name, Username) -> catch exit:ExitError -> % likely to be a problem of inequivalent args on an existing stream - rabbit_log:error("Error while creating ~tp super stream exchange: " + ?LOG_ERROR("Error while creating ~tp super stream exchange: " "~tp", [Name, ExitError]), {error, validation_failed} diff --git a/deps/rabbitmq_stream/src/rabbit_stream_reader.erl b/deps/rabbitmq_stream/src/rabbit_stream_reader.erl index a265a001ca1a..0407bfe27e2f 100644 --- a/deps/rabbitmq_stream/src/rabbit_stream_reader.erl +++ b/deps/rabbitmq_stream/src/rabbit_stream_reader.erl @@ -24,6 +24,7 @@ -include("rabbit_stream_metrics.hrl"). -include_lib("rabbitmq_stream_common/include/rabbit_stream.hrl"). +-include_lib("kernel/include/logger.hrl"). -record(statem_data, {transport :: module(), @@ -122,7 +123,7 @@ terminate(Reason, State, close(Transport, Connection, ConnectionState), rabbit_networking:unregister_non_amqp_connection(self()), notify_connection_closed(StatemData), - rabbit_log:debug("~ts terminating in state '~ts' with reason '~W'", + ?LOG_DEBUG("~ts terminating in state '~ts' with reason '~W'", [?MODULE, State, Reason, 10]). start_link(KeepaliveSup, Transport, Ref, Opts) -> @@ -458,7 +459,7 @@ handle_info(Msg, State#stream_connection_state{blocked = true}}}; Unknown -> - rabbit_log:warning("Received unknown message ~tp", [Unknown]), + ?LOG_WARNING("Received unknown message ~tp", [Unknown]), close_immediately(Transport, S), stop end. @@ -740,7 +741,7 @@ open(info, stream_from_consumers(SubId, Consumers0) end, - rabbit_log:debug("Subscription ~tp on ~tp instructed to become active: " + ?LOG_DEBUG("Subscription ~tp on ~tp instructed to become active: " "~tp", [SubId, Stream, Active]), {Connection1, ConnState1} = @@ -759,7 +760,7 @@ open(info, {false, undefined} -> undefined; {false, L} -> - rabbit_log:debug("Closing Osiris segment of subscription ~tp for " + ?LOG_DEBUG("Closing Osiris segment of subscription ~tp for " "now", [SubId]), osiris_log:close(L), @@ -786,20 +787,20 @@ open(info, => Consumer1}}}; false -> - rabbit_log:warning("Received SAC event for subscription ~tp, which " + ?LOG_WARNING("Received SAC event for subscription ~tp, which " "is not a SAC. Not doing anything.", [SubId]), {Connection0, ConnState0} end; _ -> - rabbit_log:debug("Subscription ~tp on ~tp has been deleted.", + ?LOG_DEBUG("Subscription ~tp on ~tp has been deleted.", [SubId, Stream]), - rabbit_log:debug("Active ~tp, message ~tp", [Active, Msg]), + ?LOG_DEBUG("Active ~tp, message ~tp", [Active, Msg]), _ = case {Active, Msg} of {false, #{stepping_down := true, stream := St, consumer_name := ConsumerName}} -> - rabbit_log:debug("Former active consumer gone, activating consumer " ++ + ?LOG_DEBUG("Former active consumer gone, activating consumer " ++ "on stream ~tp, group ~tp", [St, ConsumerName]), sac_activate_consumer(VirtualHost, St, ConsumerName); _ -> @@ -889,13 +890,13 @@ open(info, check_outstanding_requests, request_timeout = Timeout} = Connection0} = StatemData) -> Time = erlang:monotonic_time(millisecond), - rabbit_log:debug("Checking outstanding requests at ~tp: ~tp", [Time, Requests]), + ?LOG_DEBUG("Checking outstanding requests at ~tp: ~tp", [Time, Requests]), HasTimedOut = maps:fold(fun(_, #request{}, true) -> true; (K, #request{content = Ctnt, start = Start}, false) -> case (Time - Start) > Timeout of true -> - rabbit_log:debug("Request ~tp with content ~tp has timed out", + ?LOG_DEBUG("Request ~tp with content ~tp has timed out", [K, Ctnt]), true; @@ -1051,7 +1052,7 @@ open(cast, {queue_event, #resource{name = StreamName}, {osiris_offset, _QueueResource, -1}}, _StatemData) -> - rabbit_log:debug("Stream protocol connection received osiris offset " + ?LOG_DEBUG("Stream protocol connection received osiris offset " "event for ~tp with offset ~tp", [StreamName, -1]), keep_state_and_data; @@ -1072,13 +1073,13 @@ open(cast, {Connection1, State1} = case maps:get(StreamName, StreamSubscriptions, undefined) of undefined -> - rabbit_log:debug("Stream protocol connection: osiris offset event " + ?LOG_DEBUG("Stream protocol connection: osiris offset event " "for ~tp, but no subscription (leftover messages " "after unsubscribe?)", [StreamName]), {Connection, State}; [] -> - rabbit_log:debug("Stream protocol connection: osiris offset event " + ?LOG_DEBUG("Stream protocol connection: osiris offset event " "for ~tp, but no registered consumers!", [StreamName]), {Connection#stream_connection{stream_subscriptions = @@ -1183,7 +1184,7 @@ close_sent(info, {tcp_error, S, Reason}, #statem_data{}) -> stop; close_sent(info, {resource_alarm, IsThereAlarm}, StatemData = #statem_data{connection = Connection}) -> - rabbit_log:warning("Stream protocol connection ignored a resource " + ?LOG_WARNING("Stream protocol connection ignored a resource " "alarm ~tp in state ~ts", [IsThereAlarm, ?FUNCTION_NAME]), {keep_state, @@ -1463,7 +1464,7 @@ handle_frame_pre_auth(Transport, State, {request, CorrelationId, {open, VirtualHost}}) -> %% FIXME enforce connection limit (see rabbit_reader:is_over_connection_limit/2) - rabbit_log:debug("Open frame received for ~ts", [VirtualHost]), + ?LOG_DEBUG("Open frame received for ~ts", [VirtualHost]), Connection1 = try rabbit_access_control:check_vhost_access(User, @@ -1491,7 +1492,7 @@ handle_frame_pre_auth(Transport, #{<<"advertised_host">> => AdvertisedHost, <<"advertised_port">> => AdvertisedPort}, - rabbit_log:debug("sending open response ok ~ts", [VirtualHost]), + ?LOG_DEBUG("sending open response ok ~ts", [VirtualHost]), Frame = rabbit_stream_core:frame({response, CorrelationId, {open, ?RESPONSE_CODE_OK, @@ -1505,7 +1506,7 @@ handle_frame_pre_auth(Transport, virtual_host = VirtualHost}), Conn catch exit:#amqp_error{explanation = Explanation} -> - rabbit_log:warning("Opening connection failed: ~ts", [Explanation]), + ?LOG_WARNING("Opening connection failed: ~ts", [Explanation]), silent_close_delay(), F = rabbit_stream_core:frame({response, CorrelationId, {open, @@ -1517,7 +1518,7 @@ handle_frame_pre_auth(Transport, {Connection1, State}; handle_frame_pre_auth(_Transport, Connection, State, heartbeat) -> - rabbit_log:debug("Received heartbeat frame pre auth"), + ?LOG_DEBUG("Received heartbeat frame pre auth"), {Connection, State}; handle_frame_pre_auth(_Transport, Connection, State, Command) -> rabbit_log_connection:warning("unknown command ~w, closing connection.", @@ -1585,7 +1586,7 @@ handle_frame_post_auth(Transport, S1, {request, CorrelationId, {sasl_authenticate, NewMechanism, NewSaslBin}}) -> - rabbit_log:debug("Open frame received sasl_authenticate for username '~ts'", [Username]), + ?LOG_DEBUG("Open frame received sasl_authenticate for username '~ts'", [Username]), {Connection1, State1} = case Auth_Mechanism of @@ -1631,7 +1632,7 @@ handle_frame_post_auth(Transport, [], C1, S1), - rabbit_log:debug("Successfully updated secret for username '~ts'", [Username]), + ?LOG_DEBUG("Successfully updated secret for username '~ts'", [Username]), {C1#stream_connection{user = NewUser, authentication_state = done, connection_step = authenticated}, @@ -1766,7 +1767,7 @@ handle_frame_post_auth(Transport, State} end; {PublisherIdTaken, ReferenceTaken} -> - rabbit_log:warning("Error while declaring publisher ~tp for stream '~ts', " + ?LOG_WARNING("Error while declaring publisher ~tp for stream '~ts', " "with reference '~ts'. ID already taken: ~tp. " "Reference already taken: ~tp.", [PublisherId, Stream, WriterRef, @@ -1981,7 +1982,7 @@ handle_frame_post_auth(Transport, increase_protocol_counter(?SUBSCRIPTION_ID_ALREADY_EXISTS), {Connection, State}; false -> - rabbit_log:debug("Creating subscription ~tp to ~tp, with offset " + ?LOG_DEBUG("Creating subscription ~tp to ~tp, with offset " "specification ~tp, properties ~0p", [SubscriptionId, Stream, @@ -1992,7 +1993,7 @@ handle_frame_post_auth(Transport, case {Sac, ConsumerName} of {true, undefined} -> - rabbit_log:warning("Cannot create subcription ~tp, a single active " + ?LOG_WARNING("Cannot create subcription ~tp, a single active " "consumer must have a name", [SubscriptionId]), response(Transport, @@ -2030,7 +2031,7 @@ handle_frame_post_auth(Transport, %% the consumer is not active, it's likely to be credit leftovers %% from a formerly active consumer. Taking the credits, %% logging and sending an error - rabbit_log:debug("Giving credit to an inactive consumer: ~tp", + ?LOG_DEBUG("Giving credit to an inactive consumer: ~tp", [SubscriptionId]), #consumer{credit = AvailableCredit} = Consumer, Consumer1 = Consumer#consumer{credit = AvailableCredit + Credit}, @@ -2067,7 +2068,7 @@ handle_frame_post_auth(Transport, Consumer1}}} end; _ -> - rabbit_log:warning("Giving credit to unknown subscription: ~tp", + ?LOG_WARNING("Giving credit to unknown subscription: ~tp", [SubscriptionId]), Code = ?RESPONSE_CODE_SUBSCRIPTION_ID_DOES_NOT_EXIST, @@ -2092,7 +2093,7 @@ handle_frame_post_auth(_Transport, ok -> store_offset(Reference, Stream, Offset, Connection0); _ -> - rabbit_log:warning("Not authorized to store offset on stream ~tp", + ?LOG_WARNING("Not authorized to store offset on stream ~tp", [Stream]), Connection0 end @@ -2180,7 +2181,7 @@ handle_frame_post_auth(Transport, {ok, #{leader_node := LeaderPid, replica_nodes := ReturnedReplicas}} -> - rabbit_log:debug("Created stream cluster with leader on ~tp and " + ?LOG_DEBUG("Created stream cluster with leader on ~tp and " "replicas on ~tp", [LeaderPid, ReturnedReplicas]), response_ok(Transport, @@ -2344,8 +2345,8 @@ handle_frame_post_auth(Transport, case {is_binary(Host), is_integer(Port)} of {true, true} -> Acc#{Node => {Host, Port}}; _ -> - rabbit_log:warning("Error when retrieving broker '~tp' metadata: ~tp ~tp", - [Node, Host, Port]), + ?LOG_WARNING("Error when retrieving broker '~tp' metadata: ~tp ~tp", + [Node, Host, Port]), Acc end end, @@ -2444,13 +2445,13 @@ handle_frame_post_auth(Transport, ?RESPONSE_CODE_OK -> ok; RC -> - rabbit_log:info("Unexpected consumer update response code: ~tp", + ?LOG_INFO("Unexpected consumer update response code: ~tp", [RC]) end, case maps:take(CorrelationId, Requests0) of {#request{content = #{subscription_id := SubscriptionId} = Msg}, Rs} -> Stream = stream_from_consumers(SubscriptionId, Consumers), - rabbit_log:debug("Received consumer update response for subscription " + ?LOG_DEBUG("Received consumer update response for subscription " "~tp on stream ~tp, correlation ID ~tp", [SubscriptionId, Stream, CorrelationId]), Consumers1 = @@ -2478,7 +2479,7 @@ handle_frame_post_auth(Transport, ROS end, - rabbit_log:debug("Initializing reader for active consumer " + ?LOG_DEBUG("Initializing reader for active consumer " "(subscription ~tp, stream ~tp), offset " "spec is ~tp", [SubscriptionId, Stream, OffsetSpec]), @@ -2499,7 +2500,7 @@ handle_frame_post_auth(Transport, send_limit = SndLmt, configuration = #consumer_configuration{counters = ConsumerCounters}} = Consumer1, - rabbit_log:debug("Dispatching to subscription ~tp (stream ~tp), " + ?LOG_DEBUG("Dispatching to subscription ~tp (stream ~tp), " "credit(s) ~tp, send limit ~tp", [SubscriptionId, Stream, @@ -2531,7 +2532,7 @@ handle_frame_post_auth(Transport, ConsumerOffset = osiris_log:next_offset(Log2), ConsumedMessagesAfter = messages_consumed(ConsumerCounters), - rabbit_log:debug("Subscription ~tp (stream ~tp) is now at offset ~tp with ~tp " + ?LOG_DEBUG("Subscription ~tp (stream ~tp) is now at offset ~tp with ~tp " "message(s) distributed after subscription", [SubscriptionId, Stream, @@ -2545,12 +2546,12 @@ handle_frame_post_auth(Transport, stream = Stream, properties = Properties}}} -> - rabbit_log:debug("Not an active consumer"), + ?LOG_DEBUG("Not an active consumer"), case Msg of #{stepping_down := true} -> ConsumerName = consumer_name(Properties), - rabbit_log:debug("Subscription ~tp on stream ~tp, group ~tp " ++ + ?LOG_DEBUG("Subscription ~tp on stream ~tp, group ~tp " ++ "has stepped down, activating consumer", [SubscriptionId, Stream, ConsumerName]), _ = sac_activate_consumer(VirtualHost, Stream, @@ -2562,7 +2563,7 @@ handle_frame_post_auth(Transport, Consumers; _ -> - rabbit_log:debug("No consumer found for subscription ~tp", + ?LOG_DEBUG("No consumer found for subscription ~tp", [SubscriptionId]), Consumers end, @@ -2570,12 +2571,12 @@ handle_frame_post_auth(Transport, {Connection#stream_connection{outstanding_requests = Rs}, State#stream_connection_state{consumers = Consumers1}}; {V, _Rs} -> - rabbit_log:warning("Unexpected outstanding requests for correlation " + ?LOG_WARNING("Unexpected outstanding requests for correlation " "ID ~tp: ~tp", [CorrelationId, V]), {Connection, State}; error -> - rabbit_log:warning("Could not find outstanding consumer update request " + ?LOG_WARNING("Could not find outstanding consumer update request " "with correlation ID ~tp. No actions taken for " "the subscription.", [CorrelationId]), @@ -2656,14 +2657,14 @@ handle_frame_post_auth(Transport, BindingKeys, Username) of ok -> - rabbit_log:debug("Created super stream ~tp", [SuperStreamName]), + ?LOG_DEBUG("Created super stream ~tp", [SuperStreamName]), response_ok(Transport, Connection, create_super_stream, CorrelationId), {Connection, State}; {error, {validation_failed, Msg}} -> - rabbit_log:warning("Error while trying to create super stream ~tp: ~tp", + ?LOG_WARNING("Error while trying to create super stream ~tp: ~tp", [SuperStreamName, Msg]), response(Transport, Connection, @@ -2673,7 +2674,7 @@ handle_frame_post_auth(Transport, increase_protocol_counter(?PRECONDITION_FAILED), {Connection, State}; {error, {reference_already_exists, Msg}} -> - rabbit_log:warning("Error while trying to create super stream ~tp: ~tp", + ?LOG_WARNING("Error while trying to create super stream ~tp: ~tp", [SuperStreamName, Msg]), response(Transport, Connection, @@ -2683,7 +2684,7 @@ handle_frame_post_auth(Transport, increase_protocol_counter(?STREAM_ALREADY_EXISTS), {Connection, State}; {error, Error} -> - rabbit_log:warning("Error while trying to create super stream ~tp: ~tp", + ?LOG_WARNING("Error while trying to create super stream ~tp: ~tp", [SuperStreamName, Error]), response(Transport, Connection, @@ -2762,7 +2763,7 @@ handle_frame_post_auth(Transport, State, {request, CorrelationId, {close, ClosingCode, ClosingReason}}) -> - rabbit_log:debug("Stream protocol reader received close command " + ?LOG_DEBUG("Stream protocol reader received close command " "~tp ~tp", [ClosingCode, ClosingReason]), Frame = @@ -2772,13 +2773,13 @@ handle_frame_post_auth(Transport, {Connection#stream_connection{connection_step = closing}, State}; %% we ignore any subsequent frames handle_frame_post_auth(_Transport, Connection, State, heartbeat) -> - rabbit_log:debug("Received heartbeat frame post auth"), + ?LOG_DEBUG("Received heartbeat frame post auth"), {Connection, State}; handle_frame_post_auth(Transport, #stream_connection{socket = S} = Connection, State, Command) -> - rabbit_log:warning("unknown command ~tp, sending close command.", + ?LOG_WARNING("unknown command ~tp, sending close command.", [Command]), CloseReason = <<"unknown frame">>, Frame = @@ -2811,7 +2812,7 @@ init_reader(ConnectionTransport, rabbit_stream_utils:filter_spec(Properties)), {ok, Segment} = osiris:init_reader(LocalMemberPid, OffsetSpec, CounterSpec, Options), - rabbit_log:debug("Next offset for subscription ~tp is ~tp", + ?LOG_DEBUG("Next offset for subscription ~tp is ~tp", [SubscriptionId, osiris_log:next_offset(Segment)]), Segment. @@ -2840,7 +2841,7 @@ maybe_dispatch_on_subscription(Transport, SubscriptionProperties, SendFileOct, false = _Sac) -> - rabbit_log:debug("Distributing existing messages to subscription " + ?LOG_DEBUG("Distributing existing messages to subscription " "~tp on ~tp", [SubscriptionId, Stream]), case send_chunks(DeliverVersion, @@ -2864,7 +2865,7 @@ maybe_dispatch_on_subscription(Transport, ConsumerOffset = osiris_log:next_offset(Log1), ConsumerOffsetLag = consumer_i(offset_lag, ConsumerState1), - rabbit_log:debug("Subscription ~tp on ~tp is now at offset ~tp with ~tp " + ?LOG_DEBUG("Subscription ~tp on ~tp is now at offset ~tp with ~tp " "message(s) distributed after subscription", [SubscriptionId, Stream, ConsumerOffset, messages_consumed(ConsumerCounters1)]), @@ -2891,7 +2892,7 @@ maybe_dispatch_on_subscription(_Transport, SubscriptionProperties, _SendFileOct, true = _Sac) -> - rabbit_log:debug("No initial dispatch for subscription ~tp for " + ?LOG_DEBUG("No initial dispatch for subscription ~tp for " "now, waiting for consumer update response from " "client (single active consumer)", [SubscriptionId]), @@ -3000,7 +3001,7 @@ handle_subscription(Transport,#stream_connection{ StreamSubscriptions1}, State1}; {error, Reason} -> - rabbit_log:warning("Cannot create SAC subcription ~tp: ~tp", + ?LOG_WARNING("Cannot create SAC subcription ~tp: ~tp", [SubscriptionId, Reason]), response(Transport, Connection, @@ -3037,7 +3038,7 @@ maybe_send_consumer_update(Transport, register_request(#stream_connection{outstanding_requests = Requests0, correlation_id_sequence = CorrIdSeq} = C, RequestContent) -> - rabbit_log:debug("Registering RPC request ~tp with correlation ID ~tp", + ?LOG_DEBUG("Registering RPC request ~tp with correlation ID ~tp", [RequestContent, CorrIdSeq]), Requests1 = maps:put(CorrIdSeq, request(RequestContent), Requests0), @@ -3122,14 +3123,14 @@ ensure_outstanding_requests_timer(C) -> ensure_token_expiry_timer(User, #stream_connection{token_expiry_timer = Timer} = Conn) -> TimerRef = maybe - rabbit_log:debug("Checking token expiry"), + ?LOG_DEBUG("Checking token expiry"), true ?= rabbit_access_control:permission_cache_can_expire(User), - rabbit_log:debug("Token can expire"), + ?LOG_DEBUG("Token can expire"), Ts = rabbit_access_control:expiry_timestamp(User), - rabbit_log:debug("Token expiry timestamp: ~tp", [Ts]), + ?LOG_DEBUG("Token expiry timestamp: ~tp", [Ts]), true ?= is_integer(Ts), Time = (Ts - os:system_time(second)) * 1000, - rabbit_log:debug("Token expires in ~tp ms, setting timer to close connection", [Time]), + ?LOG_DEBUG("Token expires in ~tp ms, setting timer to close connection", [Time]), true ?= Time > 0, erlang:send_after(Time, self(), token_expired) else @@ -3167,7 +3168,7 @@ maybe_unregister_consumer(VirtualHost, when SubId =:= SubscriptionId -> _ = sac_activate_consumer(VirtualHost, Stream, ConsumerName), - rabbit_log:debug("Outstanding SAC activation request for stream '~tp', " ++ + ?LOG_DEBUG("Outstanding SAC activation request for stream '~tp', " ++ "group '~tp', sending activation.", [Stream, ConsumerName]), Acc; @@ -3394,12 +3395,12 @@ clean_publishers(MemberPid, Stream, S0}. store_offset(Reference, _, _, C) when ?IS_INVALID_REF(Reference) -> - rabbit_log:warning("Reference is too long to store offset: ~p", [byte_size(Reference)]), + ?LOG_WARNING("Reference is too long to store offset: ~p", [byte_size(Reference)]), C; store_offset(Reference, Stream, Offset, Connection0) -> case lookup_leader(Stream, Connection0) of {error, Error} -> - rabbit_log:warning("Could not find leader to store offset on ~tp: " + ?LOG_WARNING("Could not find leader to store offset on ~tp: " "~tp", [Stream, Error]), Connection0; @@ -3443,7 +3444,7 @@ remove_subscription(SubscriptionId, #consumer{log = Log, configuration = #consumer_configuration{stream = Stream, member_pid = MemberPid}} = Consumer, - rabbit_log:debug("Deleting subscription ~tp (stream ~tp)", + ?LOG_DEBUG("Deleting subscription ~tp (stream ~tp)", [SubscriptionId, Stream]), close_log(Log), #{Stream := SubscriptionsForThisStream} = StreamSubscriptions, @@ -4053,7 +4054,7 @@ sac_call(Call) -> true -> Err; _ -> - rabbit_log:info("Stream SAC coordinator call failed with ~tp", + ?LOG_INFO("Stream SAC coordinator call failed with ~tp", [Reason]), throw({stop, {shutdown, stream_sac_coordinator_error}}) end; diff --git a/deps/rabbitmq_stream/src/rabbit_stream_utils.erl b/deps/rabbitmq_stream/src/rabbit_stream_utils.erl index 964659021a36..74cc2ed60102 100644 --- a/deps/rabbitmq_stream/src/rabbit_stream_utils.erl +++ b/deps/rabbitmq_stream/src/rabbit_stream_utils.erl @@ -40,6 +40,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include_lib("rabbitmq_stream_common/include/rabbit_stream.hrl"). +-include_lib("kernel/include/logger.hrl"). enforce_correct_name(Name) -> % from rabbit_channel @@ -155,7 +156,7 @@ auth_mechanisms(Sock) -> auth_mechanism_to_module(TypeBin, Sock) -> case rabbit_registry:binary_to_type(TypeBin) of {error, not_found} -> - rabbit_log:warning("Unknown authentication mechanism '~tp'", + ?LOG_WARNING("Unknown authentication mechanism '~tp'", [TypeBin]), {error, not_found}; T -> @@ -166,7 +167,7 @@ auth_mechanism_to_module(TypeBin, Sock) -> {true, {ok, Module}} -> {ok, Module}; _ -> - rabbit_log:warning("Invalid authentication mechanism '~tp'", + ?LOG_WARNING("Invalid authentication mechanism '~tp'", [T]), {error, invalid} end diff --git a/deps/rabbitmq_stream_management/src/rabbit_stream_mgmt_db.erl b/deps/rabbitmq_stream_management/src/rabbit_stream_mgmt_db.erl index 7feb0ea91312..07ad00d10b3a 100644 --- a/deps/rabbitmq_stream_management/src/rabbit_stream_mgmt_db.erl +++ b/deps/rabbitmq_stream_management/src/rabbit_stream_mgmt_db.erl @@ -12,6 +12,7 @@ -include_lib("rabbitmq_stream/include/rabbit_stream_metrics.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([get_all_consumers/1, get_all_publishers/1]). @@ -183,7 +184,7 @@ ets_select(T, Spec) -> ets:select(T, Spec) catch error:Reason -> %% badarg can occur if the table has no been created yet - rabbit_log:warning("Error while querying ETS table '~tp': ~tp", + ?LOG_WARNING("Error while querying ETS table '~tp': ~tp", [T, Reason]), [] end. diff --git a/deps/rabbitmq_tracing/src/rabbit_tracing_consumer.erl b/deps/rabbitmq_tracing/src/rabbit_tracing_consumer.erl index cf08b6981fd6..d7b3bc1cdbf8 100644 --- a/deps/rabbitmq_tracing/src/rabbit_tracing_consumer.erl +++ b/deps/rabbitmq_tracing/src/rabbit_tracing_consumer.erl @@ -10,6 +10,7 @@ -behaviour(gen_server). -include_lib("amqp_client/include/amqp_client.hrl"). +-include_lib("kernel/include/logger.hrl"). -import(rabbit_misc, [pget/2, pget/3, table_lookup/2]). @@ -75,7 +76,7 @@ init(Args0) -> {ok, F} -> rabbit_tracing_traces:announce(VHost, Name, self()), Format = list_to_atom(binary_to_list(pget(format, Args))), - rabbit_log:info("Tracer opened log file ~tp with " + ?LOG_INFO("Tracer opened log file ~tp with " "format ~tp", [Filename, Format]), {ok, #state{conn = Conn, ch = Ch, vhost = VHost, queue = Q, file = F, filename = Filename, @@ -119,7 +120,7 @@ terminate(shutdown, State = #state{conn = Conn, ch = Ch, catch amqp_channel:close(Ch), catch amqp_connection:close(Conn), catch prim_file:close(F), - rabbit_log:info("Tracer closed log file ~tp", [Filename]), + ?LOG_INFO("Tracer closed log file ~tp", [Filename]), ok; terminate(_Reason, _State) -> diff --git a/deps/rabbitmq_tracing/src/rabbit_tracing_files.erl b/deps/rabbitmq_tracing/src/rabbit_tracing_files.erl index 84e95ff5e4ee..f702896c6387 100644 --- a/deps/rabbitmq_tracing/src/rabbit_tracing_files.erl +++ b/deps/rabbitmq_tracing/src/rabbit_tracing_files.erl @@ -8,6 +8,7 @@ -module(rabbit_tracing_files). -include_lib("kernel/include/file.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([list/0, exists/1, delete/1, full_path/1]). @@ -41,7 +42,7 @@ file_info(Name) -> {ok, Info} -> Info#file_info.size; {error, Error} -> - rabbit_log:warning("error getting file info for ~ts: ~tp", + ?LOG_WARNING("error getting file info for ~ts: ~tp", [Name, Error]), 0 end, diff --git a/deps/rabbitmq_tracing/src/rabbit_tracing_util.erl b/deps/rabbitmq_tracing/src/rabbit_tracing_util.erl index cb1a927beaed..5345951c29bc 100644 --- a/deps/rabbitmq_tracing/src/rabbit_tracing_util.erl +++ b/deps/rabbitmq_tracing/src/rabbit_tracing_util.erl @@ -7,6 +7,9 @@ -module(rabbit_tracing_util). +-include_lib("kernel/include/logger.hrl"). + + -export([coerce_env_value/2]). -export([apply_on_node/5]). @@ -24,7 +27,7 @@ apply_on_node(ReqData, Context, Mod, Fun, Args) -> {badrpc, _} = Error -> Msg = io_lib:format("Node ~tp could not be contacted: ~tp", [Node, Error]), - rabbit_log:warning(Msg, []), + ?LOG_WARNING(Msg, []), rabbit_mgmt_util:bad_request(list_to_binary(Msg), ReqData, Context); Any -> Any diff --git a/deps/rabbitmq_trust_store/src/rabbit_trust_store.erl b/deps/rabbitmq_trust_store/src/rabbit_trust_store.erl index a3716da76e25..8fe67e84d991 100644 --- a/deps/rabbitmq_trust_store/src/rabbit_trust_store.erl +++ b/deps/rabbitmq_trust_store/src/rabbit_trust_store.erl @@ -19,6 +19,7 @@ -include_lib("stdlib/include/ms_transform.hrl"). -include_lib("public_key/include/public_key.hrl"). +-include_lib("kernel/include/logger.hrl"). -type certificate() :: #'OTPCertificate'{}. -type event() :: valid_peer @@ -154,12 +155,12 @@ handle_info(refresh, #state{refresh_interval = Interval, providers_state = ProvidersState} = St) -> Config = application:get_all_env(rabbitmq_trust_store), try - rabbit_log:debug("Trust store will attempt to refresh certificates..."), + ?LOG_DEBUG("Trust store will attempt to refresh certificates..."), NewProvidersState = refresh_certs(Config, ProvidersState), {noreply, St#state{providers_state = NewProvidersState}} catch _:Error -> - rabbit_log:error("Failed to refresh certificates: ~tp", [Error]), + ?LOG_ERROR("Failed to refresh certificates: ~tp", [Error]), {noreply, St#state{providers_state = ProvidersState}} after erlang:send_after(Interval, erlang:self(), refresh) @@ -222,17 +223,17 @@ refresh_certs(Config, State) -> refresh_provider_certs(Provider, Config, ProviderState) -> case list_certs(Provider, Config, ProviderState) of no_change -> - rabbit_log:debug("Trust store provider reported no certificate changes"), + ?LOG_DEBUG("Trust store provider reported no certificate changes"), ProviderState; ok -> - rabbit_log:debug("Trust store provider reported no certificate changes"), + ?LOG_DEBUG("Trust store provider reported no certificate changes"), ProviderState; {ok, CertsList, NewProviderState} -> - rabbit_log:debug("Trust store listed certificates: ~tp", [CertsList]), + ?LOG_DEBUG("Trust store listed certificates: ~tp", [CertsList]), update_certs(CertsList, Provider, Config), NewProviderState; {error, Reason} -> - rabbit_log:error("Unable to load certificate list for provider ~tp," + ?LOG_ERROR("Unable to load certificate list for provider ~tp," " reason: ~tp", [Provider, Reason]), ProviderState @@ -244,7 +245,7 @@ list_certs(Provider, Config, ProviderState) -> Provider:list_certs(Config, ProviderState). update_certs(CertsList, Provider, Config) -> - rabbit_log:debug("Updating ~tp fetched trust store certificates", [length(CertsList)]), + ?LOG_DEBUG("Updating ~tp fetched trust store certificates", [length(CertsList)]), OldCertIds = get_old_cert_ids(Provider), {NewCertIds, _} = lists:unzip(CertsList), @@ -256,7 +257,7 @@ update_certs(CertsList, Provider, Config) -> {ok, Cert, IssuerId} -> save_cert(CertId, Provider, IssuerId, Cert, Name); {error, Reason} -> - rabbit_log:error("Unable to load CA certificate ~tp" + ?LOG_ERROR("Unable to load CA certificate ~tp" " with provider ~tp," " reason: ~tp", [CertId, Provider, Reason]) @@ -311,7 +312,7 @@ providers(Config) -> case code:ensure_loaded(Provider) of {module, Provider} -> true; {error, Error} -> - rabbit_log:warning("Unable to load trust store certificates" + ?LOG_WARNING("Unable to load trust store certificates" " with provider module ~tp. Reason: ~tp", [Provider, Error]), false diff --git a/deps/rabbitmq_trust_store/src/rabbit_trust_store_app.erl b/deps/rabbitmq_trust_store/src/rabbit_trust_store_app.erl index e90c3c8b3779..f70720ec1bae 100644 --- a/deps/rabbitmq_trust_store/src/rabbit_trust_store_app.erl +++ b/deps/rabbitmq_trust_store/src/rabbit_trust_store_app.erl @@ -6,6 +6,9 @@ %% -module(rabbit_trust_store_app). + +-include_lib("kernel/include/logger.hrl"). + -behaviour(application). -export([change_SSL_options/0]). -export([revert_SSL_options/0]). @@ -48,7 +51,7 @@ edit(Options) -> undefined -> ok; Val -> - rabbit_log:warning("RabbitMQ trust store plugin is used " + ?LOG_WARNING("RabbitMQ trust store plugin is used " "and the verify_fun TLS option is set: ~tp. " "It will be overwritten by the plugin.", [Val]), ok diff --git a/deps/rabbitmq_trust_store/src/rabbit_trust_store_file_provider.erl b/deps/rabbitmq_trust_store/src/rabbit_trust_store_file_provider.erl index 5ab65f5277e3..5a89fea70449 100644 --- a/deps/rabbitmq_trust_store/src/rabbit_trust_store_file_provider.erl +++ b/deps/rabbitmq_trust_store/src/rabbit_trust_store_file_provider.erl @@ -8,6 +8,7 @@ -module(rabbit_trust_store_file_provider). -include_lib("kernel/include/file.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(rabbit_trust_store_certificate_provider). @@ -38,7 +39,7 @@ list_certs(Config, _) -> load_cert({FileName, _, _}, _, Config) -> Path = directory_path(Config), Cert = extract_cert(Path, FileName), - rabbit_log:info( + ?LOG_INFO( "trust store: loading certificate '~ts'", [FileName]), {ok, Cert}. diff --git a/deps/rabbitmq_trust_store/src/rabbit_trust_store_http_provider.erl b/deps/rabbitmq_trust_store/src/rabbit_trust_store_http_provider.erl index a9e3b04507a4..8599b12808e1 100644 --- a/deps/rabbitmq_trust_store/src/rabbit_trust_store_http_provider.erl +++ b/deps/rabbitmq_trust_store/src/rabbit_trust_store_http_provider.erl @@ -7,6 +7,9 @@ -module(rabbit_trust_store_http_provider). +-include_lib("kernel/include/logger.hrl"). + + -behaviour(rabbit_trust_store_certificate_provider). -define(PROFILE, ?MODULE). @@ -29,14 +32,14 @@ list_certs(_, #http_state{url = Url, headers = Headers} = State) -> case (httpc:request(get, {Url, Headers}, HttpOptions, [{body_format, binary}], ?PROFILE)) of {ok, {{_, 200, _}, RespHeaders, Body}} -> - rabbit_log:debug("Trust store HTTP[S] provider responded with 200 OK"), + ?LOG_DEBUG("Trust store HTTP[S] provider responded with 200 OK"), Certs = decode_cert_list(Body), NewState = new_state(RespHeaders, State), {ok, Certs, NewState}; {ok, {{_,304, _}, _, _}} -> no_change; {ok, {{_,Code,_}, _, Body}} -> {error, {http_error, Code, Body}}; {error, Reason} -> - rabbit_log:error("Trust store HTTP[S] provider request failed: ~tp", [Reason]), + ?LOG_ERROR("Trust store HTTP[S] provider request failed: ~tp", [Reason]), {error, Reason} end. @@ -90,10 +93,10 @@ decode_cert_list(Body) -> {CertId, [{path, Path}]} end, Certs) catch _:badarg -> - rabbit_log:error("Trust store failed to decode an HTTP[S] response: JSON parser failed"), + ?LOG_ERROR("Trust store failed to decode an HTTP[S] response: JSON parser failed"), []; _:Error -> - rabbit_log:error("Trust store failed to decode an HTTP[S] response: ~tp", [Error]), + ?LOG_ERROR("Trust store failed to decode an HTTP[S] response: ~tp", [Error]), [] end. diff --git a/deps/rabbitmq_web_dispatch/src/rabbit_web_dispatch_access_control.erl b/deps/rabbitmq_web_dispatch/src/rabbit_web_dispatch_access_control.erl index a918dce2af4e..c18c258d0b76 100644 --- a/deps/rabbitmq_web_dispatch/src/rabbit_web_dispatch_access_control.erl +++ b/deps/rabbitmq_web_dispatch/src/rabbit_web_dispatch_access_control.erl @@ -9,6 +9,7 @@ -include("rabbitmq_web_dispatch_records.hrl"). -include_lib("amqp_client/include/amqp_client.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([is_authorized/3, is_authorized/7, is_authorized_admin/3, is_authorized_admin/5, vhost/1, vhost_from_headers/1]). @@ -39,7 +40,7 @@ is_authorized_admin(ReqData, Context, Username, Password, AuthConfig) -> case is_basic_auth_disabled(AuthConfig) of true -> Msg = "HTTP access denied: basic auth disabled", - rabbit_log:warning(Msg), + ?LOG_WARNING(Msg), not_authorised(Msg, ReqData, Context); false -> is_authorized(ReqData, Context, Username, Password, @@ -91,7 +92,7 @@ is_authorized1(ReqData, Context, ErrorMsg, Fun, AuthConfig) -> case is_basic_auth_disabled(AuthConfig) of true -> Msg = "HTTP access denied: basic auth disabled", - rabbit_log:warning(Msg), + ?LOG_WARNING(Msg), not_authorised(Msg, ReqData, Context); false -> is_authorized(ReqData, Context, @@ -107,7 +108,7 @@ is_authorized1(ReqData, Context, ErrorMsg, Fun, AuthConfig) -> case is_basic_auth_disabled(AuthConfig) of true -> Msg = "HTTP access denied: basic auth disabled", - rabbit_log:warning(Msg), + ?LOG_WARNING(Msg), not_authorised(Msg, ReqData, Context); false -> {{false, AuthConfig#auth_settings.auth_realm}, ReqData, Context} @@ -129,7 +130,7 @@ is_authorized(ReqData, Context, Username, Password, ErrorMsg, Fun, AuthConfig) - is_authorized(ReqData, Context, Username, Password, ErrorMsg, Fun, AuthConfig, ReplyWhenFailed) -> ErrFun = fun (ResolvedUserName, Msg) -> - rabbit_log:warning("HTTP access denied: user '~ts' - ~ts", + ?LOG_WARNING("HTTP access denied: user '~ts' - ~ts", [ResolvedUserName, Msg]), case ReplyWhenFailed of true -> not_authorised(Msg, ReqData, Context); @@ -171,7 +172,7 @@ is_authorized(ReqData, Context, Username, Password, ErrorMsg, Fun, AuthConfig, R end; {refused, _Username, Msg, Args} -> rabbit_core_metrics:auth_attempt_failed(IP, Username, http), - rabbit_log:warning("HTTP access denied: ~ts", + ?LOG_WARNING("HTTP access denied: ~ts", [rabbit_misc:format(Msg, Args)]), case ReplyWhenFailed of true -> not_authenticated(<<"Not_Authorized">>, ReqData, Context, AuthConfig); @@ -359,7 +360,7 @@ list_login_vhosts(User, AuthzData) -> % rabbitmq/rabbitmq-auth-backend-http#100 log_access_control_result(NotOK) -> - rabbit_log:debug("rabbit_access_control:check_vhost_access result: ~tp", [NotOK]). + ?LOG_DEBUG("rabbit_access_control:check_vhost_access result: ~tp", [NotOK]). is_basic_auth_disabled(#auth_settings{basic_auth_enabled = Enabled}) -> not Enabled. diff --git a/deps/rabbitmq_web_dispatch/src/rabbit_web_dispatch_registry.erl b/deps/rabbitmq_web_dispatch/src/rabbit_web_dispatch_registry.erl index ff5004eecfb1..3d56945db52f 100644 --- a/deps/rabbitmq_web_dispatch/src/rabbit_web_dispatch_registry.erl +++ b/deps/rabbitmq_web_dispatch/src/rabbit_web_dispatch_registry.erl @@ -7,6 +7,9 @@ -module(rabbit_web_dispatch_registry). +-include_lib("kernel/include/logger.hrl"). + + -behaviour(gen_server). -export([start_link/0]). @@ -91,7 +94,7 @@ handle_call({remove, Name}, _From, undefined) -> case listener_by_name(Name) of {error, not_found} -> - rabbit_log:warning("HTTP listener registry could not find context ~tp", + ?LOG_WARNING("HTTP listener registry could not find context ~tp", [Name]), {reply, ok, undefined}; {ok, Listener} -> @@ -116,7 +119,7 @@ handle_call(list_all, _From, undefined) -> {reply, list(), undefined}; handle_call(Req, _From, State) -> - rabbit_log:error("Unexpected call to ~tp: ~tp", [?MODULE, Req]), + ?LOG_ERROR("Unexpected call to ~tp: ~tp", [?MODULE, Req]), {stop, unknown_request, State}. handle_cast(_, State) -> diff --git a/deps/rabbitmq_web_dispatch/src/rabbit_web_dispatch_sup.erl b/deps/rabbitmq_web_dispatch/src/rabbit_web_dispatch_sup.erl index 534f4a884dec..94594e2288de 100644 --- a/deps/rabbitmq_web_dispatch/src/rabbit_web_dispatch_sup.erl +++ b/deps/rabbitmq_web_dispatch/src/rabbit_web_dispatch_sup.erl @@ -7,6 +7,9 @@ -module(rabbit_web_dispatch_sup). +-include_lib("kernel/include/logger.hrl"). + + -behaviour(supervisor). -define(SUP, ?MODULE). @@ -31,7 +34,7 @@ ensure_listener(Listener) -> TransportOpts = rabbit_ssl_options:wrap_password_opt(TransportOpts0), ProtoOptsMap = maps:from_list(ProtoOpts), StreamHandlers = stream_handlers_config(ProtoOpts), - rabbit_log:debug("Starting HTTP[S] listener with transport ~ts", [Transport]), + ?LOG_DEBUG("Starting HTTP[S] listener with transport ~ts", [Transport]), CowboyOptsMap = maps:merge(#{env => #{rabbit_listener => Listener}, diff --git a/deps/rabbitmq_web_mqtt/src/rabbit_web_mqtt_app.erl b/deps/rabbitmq_web_mqtt/src/rabbit_web_mqtt_app.erl index 9562ae3321ac..e1f7bbb55c5c 100644 --- a/deps/rabbitmq_web_mqtt/src/rabbit_web_mqtt_app.erl +++ b/deps/rabbitmq_web_mqtt/src/rabbit_web_mqtt_app.erl @@ -7,6 +7,9 @@ -module(rabbit_web_mqtt_app). +-include_lib("kernel/include/logger.hrl"). + + -behaviour(application). -export([ start/2, @@ -110,13 +113,13 @@ start_tcp_listener(TCPConf0, CowboyOpts) -> {error, {already_started, _}} -> ok; {error, ErrTCP} -> - rabbit_log:error( + ?LOG_ERROR( "Failed to start a WebSocket (HTTP) listener. Error: ~p, listener settings: ~p", [ErrTCP, TCPConf]), throw(ErrTCP) end, listener_started(?TCP_PROTOCOL, TCPConf), - rabbit_log:info("rabbit_web_mqtt: listening for HTTP connections on ~s:~w", + ?LOG_INFO("rabbit_web_mqtt: listening for HTTP connections on ~s:~w", [IpStr, Port]). @@ -138,13 +141,13 @@ start_tls_listener(TLSConf0, CowboyOpts) -> {error, {already_started, _}} -> ok; {error, ErrTLS} -> - rabbit_log:error( + ?LOG_ERROR( "Failed to start a TLS WebSocket (HTTPS) listener. Error: ~p, listener settings: ~p", [ErrTLS, TLSConf]), throw(ErrTLS) end, listener_started(?TLS_PROTOCOL, TLSConf), - rabbit_log:info("rabbit_web_mqtt: listening for HTTPS connections on ~s:~w", + ?LOG_INFO("rabbit_web_mqtt: listening for HTTPS connections on ~s:~w", [TLSIpStr, TLSPort]). listener_started(Protocol, Listener) -> diff --git a/deps/rabbitmq_web_stomp/src/rabbit_web_stomp_internal_event_handler.erl b/deps/rabbitmq_web_stomp/src/rabbit_web_stomp_internal_event_handler.erl index 8aa08ede9840..9592591df6a8 100644 --- a/deps/rabbitmq_web_stomp/src/rabbit_web_stomp_internal_event_handler.erl +++ b/deps/rabbitmq_web_stomp/src/rabbit_web_stomp_internal_event_handler.erl @@ -7,6 +7,9 @@ -module(rabbit_web_stomp_internal_event_handler). +-include_lib("kernel/include/logger.hrl"). + + -behaviour(gen_event). -export([init/1, handle_event/2, handle_call/2, handle_info/2, terminate/2, code_change/3]). @@ -19,7 +22,7 @@ init([]) -> handle_event({event, maintenance_connections_closed, _Info, _, _}, State) -> %% we should close our connections {ok, NConnections} = rabbit_web_stomp_listener:close_all_client_connections("node is being put into maintenance mode"), - rabbit_log:alert("Closed ~b local Web STOMP client connections", [NConnections]), + ?LOG_INFO("Closed ~b local Web STOMP client connections", [NConnections]), {ok, State}; handle_event(_Event, State) -> {ok, State}. From b6b766cac70941a85df032008f618d76e5627d6b Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Fri, 11 Jul 2025 13:07:08 +0200 Subject: [PATCH 02/31] [skip ci] Replace logger: calls is LOG_ macros --- .../src/amqp10_client_connection.erl | 5 +++-- .../src/amqp10_client_frame_reader.erl | 13 ++++++------ .../src/amqp10_client_internal.hrl | 2 +- .../src/amqp10_client_session.erl | 10 +++++---- .../include/amqp_client_internal.hrl | 5 ----- deps/amqp_client/src/amqp_channel.erl | 21 ++++++++++--------- .../amqp_client/src/amqp_channels_manager.erl | 1 + deps/amqp_client/src/amqp_connection.erl | 3 ++- .../src/amqp_direct_connection.erl | 1 + deps/amqp_client/src/amqp_gen_connection.erl | 11 +++++----- deps/amqp_client/src/amqp_ssl.erl | 3 ++- deps/rabbit/src/file_handle_cache.erl | 2 +- deps/rabbit/src/pg_local.erl | 4 +++- .../src/rabbit_classic_queue_index_v2.erl | 2 +- .../src/rabbit_classic_queue_store_v2.erl | 2 +- deps/rabbit/src/rabbit_log_channel.erl | 17 ++++++++------- deps/rabbit/src/rabbit_log_connection.erl | 17 ++++++++------- deps/rabbit/src/rabbit_log_mirroring.erl | 17 ++++++++------- deps/rabbit/src/rabbit_log_prelaunch.erl | 17 ++++++++------- deps/rabbit/src/rabbit_log_queue.erl | 17 ++++++++------- deps/rabbit/src/rabbit_node_monitor.erl | 6 +++--- deps/rabbit/src/rabbit_time_travel_dbg.erl | 5 ++++- deps/rabbit/src/tcp_listener.erl | 9 +++++--- deps/rabbit/test/classic_queue_prop_SUITE.erl | 7 ++++--- deps/rabbit/test/logging_SUITE.erl | 2 +- deps/rabbit_common/src/rabbit_env.erl | 2 +- .../src/rabbit_log_ldap.erl | 17 ++++++++------- .../src/uaa_jwt_jwk.erl | 5 +++-- deps/rabbitmq_aws/src/rabbitmq_aws.erl | 2 +- .../src/rabbit_federation_pg.erl | 5 ++++- .../src/rabbit_log_federation.erl | 17 ++++++++------- .../src/rabbit_prelaunch_sighandler.erl | 7 +++++-- .../rabbitmq_shovel/src/rabbit_log_shovel.erl | 17 ++++++++------- .../src/rabbit_stream_core.erl | 3 ++- .../src/webmachine_log.erl | 5 +++-- .../src/trust_store_list_handler.erl | 3 ++- 36 files changed, 157 insertions(+), 125 deletions(-) diff --git a/deps/amqp10_client/src/amqp10_client_connection.erl b/deps/amqp10_client/src/amqp10_client_connection.erl index ac1d8a263cf1..d075c27e82cc 100644 --- a/deps/amqp10_client/src/amqp10_client_connection.erl +++ b/deps/amqp10_client/src/amqp10_client_connection.erl @@ -12,6 +12,7 @@ -include("amqp10_client_internal.hrl"). -include_lib("amqp10_common/include/amqp10_framing.hrl"). -include_lib("amqp10_common/include/amqp10_types.hrl"). +-include_lib("kernel/include/logger.hrl"). %% public API -export([open/1, @@ -247,7 +248,7 @@ hdr_sent(_EvtType, {protocol_header_received, 0, 1, 0, 0}, State) -> end; hdr_sent(_EvtType, {protocol_header_received, Protocol, Maj, Min, Rev}, State) -> - logger:warning("Unsupported protocol version: ~b ~b.~b.~b", + ?LOG_WARNING("Unsupported protocol version: ~b ~b.~b.~b", [Protocol, Maj, Min, Rev]), {stop, normal, State}; hdr_sent({call, From}, begin_session, @@ -342,7 +343,7 @@ opened(info, {'DOWN', MRef, process, _, _Info}, ok = notify_closed(Config, shutdown), {stop, normal}; opened(_EvtType, Frame, State) -> - logger:warning("Unexpected connection frame ~tp when in state ~tp ", + ?LOG_WARNING("Unexpected connection frame ~tp when in state ~tp ", [Frame, State]), keep_state_and_data. diff --git a/deps/amqp10_client/src/amqp10_client_frame_reader.erl b/deps/amqp10_client/src/amqp10_client_frame_reader.erl index 1ef0836049e0..93ccf464acb4 100644 --- a/deps/amqp10_client/src/amqp10_client_frame_reader.erl +++ b/deps/amqp10_client/src/amqp10_client_frame_reader.erl @@ -10,6 +10,7 @@ -include("amqp10_client_internal.hrl"). -include_lib("amqp10_common/include/amqp10_framing.hrl"). +-include_lib("kernel/include/logger.hrl"). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). @@ -141,32 +142,32 @@ handle_event(info, {gun_ws, WsPid, StreamRef, WsFrame}, StateName, {binary, Bin} -> handle_socket_input(Bin, StateName, State); close -> - logger:info("peer closed AMQP over WebSocket connection in state '~s'", + ?LOG_INFO("peer closed AMQP over WebSocket connection in state '~s'", [StateName]), {stop, normal, socket_closed(State)}; {close, ReasonStatusCode, ReasonUtf8} -> - logger:info("peer closed AMQP over WebSocket connection in state '~s', reason: ~b ~ts", + ?LOG_INFO("peer closed AMQP over WebSocket connection in state '~s', reason: ~b ~ts", [StateName, ReasonStatusCode, ReasonUtf8]), {stop, {shutdown, {ReasonStatusCode, ReasonUtf8}}, socket_closed(State)} end; handle_event(info, {TcpError, _Sock, Reason}, StateName, State) when TcpError == tcp_error orelse TcpError == ssl_error -> - logger:warning("AMQP 1.0 connection socket errored, connection state: '~ts', reason: '~tp'", + ?LOG_WARNING("AMQP 1.0 connection socket errored, connection state: '~ts', reason: '~tp'", [StateName, Reason]), {stop, {error, Reason}, socket_closed(State)}; handle_event(info, {TcpClosed, _}, StateName, State) when TcpClosed == tcp_closed orelse TcpClosed == ssl_closed -> - logger:info("AMQP 1.0 connection socket was closed, connection state: '~ts'", + ?LOG_INFO("AMQP 1.0 connection socket was closed, connection state: '~ts'", [StateName]), {stop, normal, socket_closed(State)}; handle_event(info, {gun_down, WsPid, _Proto, Reason, _Streams}, StateName, #state{socket = {ws, WsPid, _StreamRef}} = State) -> - logger:warning("AMQP over WebSocket process ~p lost connection in state: '~s': ~p", + ?LOG_WARNING("AMQP over WebSocket process ~p lost connection in state: '~s': ~p", [WsPid, StateName, Reason]), {stop, Reason, socket_closed(State)}; handle_event(info, {'DOWN', _Mref, process, WsPid, Reason}, StateName, #state{socket = {ws, WsPid, _StreamRef}} = State) -> - logger:warning("AMQP over WebSocket process ~p terminated in state: '~s': ~p", + ?LOG_WARNING("AMQP over WebSocket process ~p terminated in state: '~s': ~p", [WsPid, StateName, Reason]), {stop, Reason, socket_closed(State)}; diff --git a/deps/amqp10_client/src/amqp10_client_internal.hrl b/deps/amqp10_client/src/amqp10_client_internal.hrl index 637faf897a2b..a549c47339ea 100644 --- a/deps/amqp10_client/src/amqp10_client_internal.hrl +++ b/deps/amqp10_client/src/amqp10_client_internal.hrl @@ -12,7 +12,7 @@ % -define(debug, true). -ifdef(debug). --define(DBG(F, A), error_logger:info_msg(F, A)). +-define(DBG(F, A), error_?LOG_INFO_msg(F, A)). -else. -define(DBG(F, A), ok). -endif. diff --git a/deps/amqp10_client/src/amqp10_client_session.erl b/deps/amqp10_client/src/amqp10_client_session.erl index 7a152b440a23..08dd5e54de43 100644 --- a/deps/amqp10_client/src/amqp10_client_session.erl +++ b/deps/amqp10_client/src/amqp10_client_session.erl @@ -12,6 +12,7 @@ -include("amqp10_client_internal.hrl"). -include_lib("amqp10_common/include/amqp10_framing.hrl"). -include_lib("amqp10_common/include/amqp10_types.hrl"). +-include_lib("kernel/include/logger.hrl"). %% Public API. -export(['begin'/1, @@ -434,7 +435,7 @@ mapped(cast, {Transfer0 = #'v1_0.transfer'{handle = {uint, InHandle}}, notify_credit_exhausted(Link3), {keep_state, State}; {transfer_limit_exceeded, Link3, State} -> - logger:warning("transfer_limit_exceeded for link ~tp", [Link3]), + ?LOG_WARNING("transfer_limit_exceeded for link ~tp", [Link3]), Link = detach_with_error_cond(Link3, State, ?V_1_0_LINK_ERROR_TRANSFER_LIMIT_EXCEEDED, @@ -446,7 +447,7 @@ mapped(cast, {Transfer0 = #'v1_0.transfer'{handle = {uint, InHandle}}, io_lib:format( "~s checksum error: expected ~b, actual ~b", [FooterOpt, Expected, Actual])), - logger:warning("deteaching link ~tp due to ~s", [Link2, Description]), + ?LOG_WARNING("deteaching link ~tp due to ~s", [Link2, Description]), Link = detach_with_error_cond(Link2, State0, ?V_1_0_AMQP_ERROR_DECODE_ERROR, @@ -485,7 +486,7 @@ mapped(cast, #'v1_0.disposition'{role = true, {keep_state, State#state{outgoing_unsettled = Unsettled}}; mapped(cast, Frame, State) -> - logger:warning("Unhandled session frame ~tp in state ~tp", + ?LOG_WARNING("Unhandled session frame ~tp in state ~tp", [Frame, State]), {keep_state, State}; mapped({call, From}, @@ -566,7 +567,7 @@ mapped({call, From}, Msg, State) -> {keep_state, State1, {reply, From, Reply}}; mapped(_EvtType, Msg, _State) -> - logger:warning("amqp10_session: unhandled msg in mapped state ~W", + ?LOG_WARNING("amqp10_session: unhandled msg in mapped state ~W", [Msg, 10]), keep_state_and_data. @@ -1375,6 +1376,7 @@ format_status(Status = #{data := Data0}) -> -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). +-include_lib("kernel/include/logger.hrl"). handle_session_flow_test() -> % see spec section: 2.5.6 for logic diff --git a/deps/amqp_client/include/amqp_client_internal.hrl b/deps/amqp_client/include/amqp_client_internal.hrl index def3247f2087..6a71f249c023 100644 --- a/deps/amqp_client/include/amqp_client_internal.hrl +++ b/deps/amqp_client/include/amqp_client_internal.hrl @@ -14,11 +14,6 @@ -define(MAX_CHANNEL_NUMBER, 65535). --define(LOG_DEBUG(Format), error_logger:info_msg(Format)). --define(LOG_INFO(Format, Args), error_logger:info_msg(Format, Args)). --define(LOG_WARN(Format, Args), error_logger:warning_msg(Format, Args)). --define(LOG_ERR(Format, Args), error_logger:error_msg(Format, Args)). - -define(CLIENT_CAPABILITIES, [{<<"publisher_confirms">>, bool, true}, {<<"exchange_exchange_bindings">>, bool, true}, diff --git a/deps/amqp_client/src/amqp_channel.erl b/deps/amqp_client/src/amqp_channel.erl index d46439a320f1..06e9da7fc3b9 100644 --- a/deps/amqp_client/src/amqp_channel.erl +++ b/deps/amqp_client/src/amqp_channel.erl @@ -54,6 +54,7 @@ -module(amqp_channel). -include("amqp_client_internal.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(gen_server). @@ -514,7 +515,7 @@ handle_info({bump_credit, Msg}, State) -> {noreply, State}; %% @private handle_info(timed_out_flushing_channel, State) -> - ?LOG_WARN("Channel (~tp) closing: timed out flushing while " + ?LOG_WARNING("Channel (~tp) closing: timed out flushing while " "connection closing", [self()]), {stop, timed_out_flushing_channel, State}; %% @private @@ -523,7 +524,7 @@ handle_info({'DOWN', _, process, ReturnHandler, shutdown}, {noreply, State#state{return_handler = none}}; handle_info({'DOWN', _, process, ReturnHandler, Reason}, State = #state{return_handler = {ReturnHandler, _Ref}}) -> - ?LOG_WARN("Channel (~tp): Unregistering return handler ~tp because it died. " + ?LOG_WARNING("Channel (~tp): Unregistering return handler ~tp because it died. " "Reason: ~tp", [self(), ReturnHandler, Reason]), {noreply, State#state{return_handler = none}}; %% @private @@ -532,7 +533,7 @@ handle_info({'DOWN', _, process, ConfirmHandler, shutdown}, {noreply, State#state{confirm_handler = none}}; handle_info({'DOWN', _, process, ConfirmHandler, Reason}, State = #state{confirm_handler = {ConfirmHandler, _Ref}}) -> - ?LOG_WARN("Channel (~tp): Unregistering confirm handler ~tp because it died. " + ?LOG_WARNING("Channel (~tp): Unregistering confirm handler ~tp because it died. " "Reason: ~tp", [self(), ConfirmHandler, Reason]), {noreply, State#state{confirm_handler = none}}; %% @private @@ -541,7 +542,7 @@ handle_info({'DOWN', _, process, FlowHandler, shutdown}, {noreply, State#state{flow_handler = none}}; handle_info({'DOWN', _, process, FlowHandler, Reason}, State = #state{flow_handler = {FlowHandler, _Ref}}) -> - ?LOG_WARN("Channel (~tp): Unregistering flow handler ~tp because it died. " + ?LOG_WARNING("Channel (~tp): Unregistering flow handler ~tp because it died. " "Reason: ~tp", [self(), FlowHandler, Reason]), {noreply, State#state{flow_handler = none}}; handle_info({'DOWN', _, process, QPid, _Reason}, State) -> @@ -591,13 +592,13 @@ handle_method_to_server(Method, AmqpMsg, From, Sender, Flow, {noreply, rpc_top_half(Method, build_content(AmqpMsg), From, Sender, Flow, State1)}; {ok, none, BlockReply} -> - ?LOG_WARN("Channel (~tp): discarding method ~tp in cast.~n" + ?LOG_WARNING("Channel (~tp): discarding method ~tp in cast.~n" "Reason: ~tp", [self(), Method, BlockReply]), {noreply, State}; {ok, _, BlockReply} -> {reply, BlockReply, State}; {{_, InvalidMethodMessage}, none, _} -> - ?LOG_WARN("Channel (~tp): ignoring cast of ~tp method. " ++ + ?LOG_WARNING("Channel (~tp): ignoring cast of ~tp method. " ++ InvalidMethodMessage ++ "", [self(), Method]), {noreply, State}; {{InvalidMethodReply, _}, _, _} -> @@ -779,7 +780,7 @@ handle_method_from_server1( #'basic.return'{} = BasicReturn, AmqpMsg, State = #state{return_handler = ReturnHandler}) -> _ = case ReturnHandler of - none -> ?LOG_WARN("Channel (~tp): received {~tp, ~tp} but there is " + none -> ?LOG_WARNING("Channel (~tp): received {~tp, ~tp} but there is " "no return handler registered", [self(), BasicReturn, AmqpMsg]); {Pid, _Ref} -> Pid ! {BasicReturn, AmqpMsg} @@ -794,7 +795,7 @@ handle_method_from_server1(#'basic.ack'{} = BasicAck, none, {noreply, update_confirm_set(BasicAck, State)}; handle_method_from_server1(#'basic.nack'{} = BasicNack, none, #state{confirm_handler = none} = State) -> - ?LOG_WARN("Channel (~tp): received ~tp but there is no " + ?LOG_WARNING("Channel (~tp): received ~tp but there is no " "confirm handler registered", [self(), BasicNack]), {noreply, update_confirm_set(BasicNack, State)}; handle_method_from_server1(#'basic.nack'{} = BasicNack, none, @@ -834,7 +835,7 @@ handle_connection_closing(CloseType, Reason, handle_channel_exit(Reason = #amqp_error{name = ErrorName, explanation = Expl}, State = #state{connection = Connection, number = Number}) -> %% Sent by rabbit_channel for hard errors in the direct case - ?LOG_ERR("connection ~tp, channel ~tp - error:~n~tp", + ?LOG_ERROR("connection ~tp, channel ~tp - error:~n~tp", [Connection, Number, Reason]), {true, Code, _} = ?PROTOCOL:lookup_amqp_exception(ErrorName), ReportedReason = {server_initiated_close, Code, Expl}, @@ -930,7 +931,7 @@ server_misbehaved(#amqp_error{} = AmqpError, State = #state{number = Number}) -> {0, _} -> handle_shutdown({server_misbehaved, AmqpError}, State); {_, Close} -> - ?LOG_WARN("Channel (~tp) flushing and closing due to soft " + ?LOG_WARNING("Channel (~tp) flushing and closing due to soft " "error caused by the server ~tp", [self(), AmqpError]), Self = self(), spawn(fun () -> call(Self, Close) end), diff --git a/deps/amqp_client/src/amqp_channels_manager.erl b/deps/amqp_client/src/amqp_channels_manager.erl index e55a2ca3fa15..52155c4d3dca 100644 --- a/deps/amqp_client/src/amqp_channels_manager.erl +++ b/deps/amqp_client/src/amqp_channels_manager.erl @@ -9,6 +9,7 @@ -module(amqp_channels_manager). -include("amqp_client_internal.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(gen_server). diff --git a/deps/amqp_client/src/amqp_connection.erl b/deps/amqp_client/src/amqp_connection.erl index 2d16f3882097..c5f4223ce113 100644 --- a/deps/amqp_client/src/amqp_connection.erl +++ b/deps/amqp_client/src/amqp_connection.erl @@ -59,6 +59,7 @@ -module(amqp_connection). -include("amqp_client_internal.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([open_channel/1, open_channel/2, open_channel/3, register_blocked_handler/2]). -export([start/1, start/2, close/1, close/2, close/3, close/4]). @@ -427,7 +428,7 @@ maybe_update_call_timeout(BaseTimeout, CallTimeout) ok; maybe_update_call_timeout(BaseTimeout, CallTimeout) -> EffectiveSafeCallTimeout = amqp_util:safe_call_timeout(BaseTimeout), - ?LOG_WARN("AMQP 0-9-1 client call timeout was ~tp ms, is updated to a safe effective " + ?LOG_WARNING("AMQP 0-9-1 client call timeout was ~tp ms, is updated to a safe effective " "value of ~tp ms", [CallTimeout, EffectiveSafeCallTimeout]), amqp_util:update_call_timeout(EffectiveSafeCallTimeout), ok. diff --git a/deps/amqp_client/src/amqp_direct_connection.erl b/deps/amqp_client/src/amqp_direct_connection.erl index 5fd0b6840463..4143599b230e 100644 --- a/deps/amqp_client/src/amqp_direct_connection.erl +++ b/deps/amqp_client/src/amqp_direct_connection.erl @@ -9,6 +9,7 @@ -module(amqp_direct_connection). -include("amqp_client_internal.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(amqp_gen_connection). diff --git a/deps/amqp_client/src/amqp_gen_connection.erl b/deps/amqp_client/src/amqp_gen_connection.erl index e2b44b0ceb64..25596cc69a04 100644 --- a/deps/amqp_client/src/amqp_gen_connection.erl +++ b/deps/amqp_client/src/amqp_gen_connection.erl @@ -9,6 +9,7 @@ -module(amqp_gen_connection). -include("amqp_client_internal.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(gen_server). @@ -191,7 +192,7 @@ handle_cast(channels_terminated, State) -> handle_cast({hard_error_in_channel, _Pid, Reason}, State) -> server_initiated_close(Reason, State); handle_cast({channel_internal_error, Pid, Reason}, State) -> - ?LOG_WARN("Connection (~tp) closing: internal error in channel (~tp): ~tp", + ?LOG_WARNING("Connection (~tp) closing: internal error in channel (~tp): ~tp", [self(), Pid, Reason]), internal_error(Pid, Reason, State); handle_cast({server_misbehaved, AmqpError}, State) -> @@ -205,12 +206,12 @@ handle_cast({register_blocked_handler, HandlerPid}, State) -> %% @private handle_info({'DOWN', _, process, BlockHandler, Reason}, State = #state{block_handler = {BlockHandler, _Ref}}) -> - ?LOG_WARN("Connection (~tp): Unregistering connection.{blocked,unblocked} handler ~tp because it died. " + ?LOG_WARNING("Connection (~tp): Unregistering connection.{blocked,unblocked} handler ~tp because it died. " "Reason: ~tp", [self(), BlockHandler, Reason]), {noreply, State#state{block_handler = none}}; handle_info({'EXIT', BlockHandler, Reason}, State = #state{block_handler = {BlockHandler, Ref}}) -> - ?LOG_WARN("Connection (~tp): Unregistering connection.{blocked,unblocked} handler ~tp because it died. " + ?LOG_WARNING("Connection (~tp): Unregistering connection.{blocked,unblocked} handler ~tp because it died. " "Reason: ~tp", [self(), BlockHandler, Reason]), erlang:demonitor(Ref, [flush]), {noreply, State#state{block_handler = none}}; @@ -316,13 +317,13 @@ internal_error(Pid, Reason, State) -> State). server_initiated_close(Close, State) -> - ?LOG_WARN("Connection (~tp) closing: received hard error ~tp " + ?LOG_WARNING("Connection (~tp) closing: received hard error ~tp " "from server", [self(), Close]), set_closing_state(abrupt, #closing{reason = server_initiated_close, close = Close}, State). server_misbehaved_close(AmqpError, State) -> - ?LOG_WARN("Connection (~tp) closing: server misbehaved: ~tp", + ?LOG_WARNING("Connection (~tp) closing: server misbehaved: ~tp", [self(), AmqpError]), {0, Close} = rabbit_binary_generator:map_exception(0, AmqpError, ?PROTOCOL), set_closing_state(abrupt, #closing{reason = server_misbehaved, diff --git a/deps/amqp_client/src/amqp_ssl.erl b/deps/amqp_client/src/amqp_ssl.erl index f5cfb5a48e6a..fc04bdfbfc1c 100644 --- a/deps/amqp_client/src/amqp_ssl.erl +++ b/deps/amqp_client/src/amqp_ssl.erl @@ -3,6 +3,7 @@ -include("amqp_client_internal.hrl"). -include_lib("public_key/include/public_key.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([maybe_enhance_ssl_options/1, verify_fun/3]). @@ -51,7 +52,7 @@ maybe_add_verify1(Options) -> % NB: user has explicitly set 'verify' Options; _ -> - ?LOG_WARN("Connection (~tp): certificate chain verification is not enabled for this TLS connection. " + ?LOG_WARNING("Connection (~tp): certificate chain verification is not enabled for this TLS connection. " "Please see https://rabbitmq.com/ssl.html for more information.", [self()]), Options end. diff --git a/deps/rabbit/src/file_handle_cache.erl b/deps/rabbit/src/file_handle_cache.erl index 6e4c2bfe1087..46ed39cbc4d2 100644 --- a/deps/rabbit/src/file_handle_cache.erl +++ b/deps/rabbit/src/file_handle_cache.erl @@ -1112,7 +1112,7 @@ init([AlarmSet, AlarmClear]) -> end end, ObtainLimit = obtain_limit(Limit), - logger:info("Limiting to approx ~tp file handles (~tp sockets)", + ?LOG_INFO("Limiting to approx ~tp file handles (~tp sockets)", [Limit, ObtainLimit]), Clients = ets:new(?CLIENT_ETS_TABLE, [set, private, {keypos, #cstate.pid}]), Elders = ets:new(?ELDERS_ETS_TABLE, [set, private]), diff --git a/deps/rabbit/src/pg_local.erl b/deps/rabbit/src/pg_local.erl index df43c0dcd8f0..c3e019954bda 100644 --- a/deps/rabbit/src/pg_local.erl +++ b/deps/rabbit/src/pg_local.erl @@ -34,6 +34,8 @@ %% -module(pg_local). +-include_lib("kernel/include/logger.hrl"). + -export([join/2, leave/2, get_members/1, in_group/2]). %% intended for testing only; not part of official API -export([sync/0, clear/0]). @@ -120,7 +122,7 @@ handle_call(clear, _From, S) -> {reply, ok, S}; handle_call(Request, From, S) -> - error_logger:warning_msg("The pg_local server received an unexpected message:\n" + ?LOG_WARNING("The pg_local server received an unexpected message:\n" "handle_call(~tp, ~tp, _)\n", [Request, From]), {noreply, S}. diff --git a/deps/rabbit/src/rabbit_classic_queue_index_v2.erl b/deps/rabbit/src/rabbit_classic_queue_index_v2.erl index cc776526d613..855b77e635f4 100644 --- a/deps/rabbit/src/rabbit_classic_queue_index_v2.erl +++ b/deps/rabbit/src/rabbit_classic_queue_index_v2.erl @@ -45,7 +45,7 @@ -include_lib("kernel/include/logger.hrl"). %% Set to true to get an awful lot of debug logs. -if(false). --define(DEBUG(X,Y), logger:debug("~0p: " ++ X, [?FUNCTION_NAME|Y])). +-define(DEBUG(X,Y), ?LOG_DEBUG("~0p: " ++ X, [?FUNCTION_NAME|Y])). -else. -define(DEBUG(X,Y), _ = X, _ = Y, ok). -endif. diff --git a/deps/rabbit/src/rabbit_classic_queue_store_v2.erl b/deps/rabbit/src/rabbit_classic_queue_store_v2.erl index fb89bca6a667..d324acf26ff6 100644 --- a/deps/rabbit/src/rabbit_classic_queue_store_v2.erl +++ b/deps/rabbit/src/rabbit_classic_queue_store_v2.erl @@ -60,7 +60,7 @@ %% Set to true to get an awful lot of debug logs. -if(false). --define(DEBUG(X,Y), logger:debug("~0p: " ++ X, [?FUNCTION_NAME|Y])). +-define(DEBUG(X,Y), ?LOG_DEBUG("~0p: " ++ X, [?FUNCTION_NAME|Y])). -else. -define(DEBUG(X,Y), _ = X, _ = Y, ok). -endif. diff --git a/deps/rabbit/src/rabbit_log_channel.erl b/deps/rabbit/src/rabbit_log_channel.erl index 1b28c07e8c7a..e9ffa9c46ade 100644 --- a/deps/rabbit/src/rabbit_log_channel.erl +++ b/deps/rabbit/src/rabbit_log_channel.erl @@ -19,6 +19,7 @@ none/1, none/2, none/3]). -include_lib("rabbit_common/include/logging.hrl"). +-include_lib("kernel/include/logger.hrl"). -compile({no_auto_import, [error/2, error/3]}). @@ -30,7 +31,7 @@ debug(Format, Args) -> debug(self(), Format, Args). -spec debug(pid() | [tuple()], string(), [any()]) -> 'ok'. debug(Pid, Format, Args) -> - logger:debug(Format, Args, #{pid => Pid, + ?LOG_DEBUG(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_CHAN}). -spec info(string()) -> 'ok'. @@ -41,7 +42,7 @@ info(Format, Args) -> info(self(), Format, Args). -spec info(pid() | [tuple()], string(), [any()]) -> 'ok'. info(Pid, Format, Args) -> - logger:info(Format, Args, #{pid => Pid, + ?LOG_INFO(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_CHAN}). -spec notice(string()) -> 'ok'. @@ -52,7 +53,7 @@ notice(Format, Args) -> notice(self(), Format, Args). -spec notice(pid() | [tuple()], string(), [any()]) -> 'ok'. notice(Pid, Format, Args) -> - logger:notice(Format, Args, #{pid => Pid, + ?LOG_NOTICE(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_CHAN}). -spec warning(string()) -> 'ok'. @@ -63,7 +64,7 @@ warning(Format, Args) -> warning(self(), Format, Args). -spec warning(pid() | [tuple()], string(), [any()]) -> 'ok'. warning(Pid, Format, Args) -> - logger:warning(Format, Args, #{pid => Pid, + ?LOG_WARNING(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_CHAN}). -spec error(string()) -> 'ok'. @@ -74,7 +75,7 @@ error(Format, Args) -> error(self(), Format, Args). -spec error(pid() | [tuple()], string(), [any()]) -> 'ok'. error(Pid, Format, Args) -> - logger:error(Format, Args, #{pid => Pid, + ?LOG_ERROR(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_CHAN}). -spec critical(string()) -> 'ok'. @@ -85,7 +86,7 @@ critical(Format, Args) -> critical(self(), Format, Args). -spec critical(pid() | [tuple()], string(), [any()]) -> 'ok'. critical(Pid, Format, Args) -> - logger:critical(Format, Args, #{pid => Pid, + ?LOG_CRITICAL(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_CHAN}). -spec alert(string()) -> 'ok'. @@ -96,7 +97,7 @@ alert(Format, Args) -> alert(self(), Format, Args). -spec alert(pid() | [tuple()], string(), [any()]) -> 'ok'. alert(Pid, Format, Args) -> - logger:alert(Format, Args, #{pid => Pid, + ?LOG_ALERT(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_CHAN}). -spec emergency(string()) -> 'ok'. @@ -107,7 +108,7 @@ emergency(Format, Args) -> emergency(self(), Format, Args). -spec emergency(pid() | [tuple()], string(), [any()]) -> 'ok'. emergency(Pid, Format, Args) -> - logger:emergency(Format, Args, #{pid => Pid, + ?LOG_EMERGENCY(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_CHAN}). -spec none(string()) -> 'ok'. diff --git a/deps/rabbit/src/rabbit_log_connection.erl b/deps/rabbit/src/rabbit_log_connection.erl index acc87e70e93b..cc46aae4bc28 100644 --- a/deps/rabbit/src/rabbit_log_connection.erl +++ b/deps/rabbit/src/rabbit_log_connection.erl @@ -19,6 +19,7 @@ none/1, none/2, none/3]). -include_lib("rabbit_common/include/logging.hrl"). +-include_lib("kernel/include/logger.hrl"). -compile({no_auto_import, [error/2, error/3]}). @@ -30,7 +31,7 @@ debug(Format, Args) -> debug(self(), Format, Args). -spec debug(pid() | [tuple()], string(), [any()]) -> 'ok'. debug(Pid, Format, Args) -> - logger:debug(Format, Args, #{pid => Pid, + ?LOG_DEBUG(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_CONN}). -spec info(string()) -> 'ok'. @@ -41,7 +42,7 @@ info(Format, Args) -> info(self(), Format, Args). -spec info(pid() | [tuple()], string(), [any()]) -> 'ok'. info(Pid, Format, Args) -> - logger:info(Format, Args, #{pid => Pid, + ?LOG_INFO(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_CONN}). -spec notice(string()) -> 'ok'. @@ -52,7 +53,7 @@ notice(Format, Args) -> notice(self(), Format, Args). -spec notice(pid() | [tuple()], string(), [any()]) -> 'ok'. notice(Pid, Format, Args) -> - logger:notice(Format, Args, #{pid => Pid, + ?LOG_NOTICE(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_CONN}). -spec warning(string()) -> 'ok'. @@ -63,7 +64,7 @@ warning(Format, Args) -> warning(self(), Format, Args). -spec warning(pid() | [tuple()], string(), [any()]) -> 'ok'. warning(Pid, Format, Args) -> - logger:warning(Format, Args, #{pid => Pid, + ?LOG_WARNING(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_CONN}). -spec error(string()) -> 'ok'. @@ -74,7 +75,7 @@ error(Format, Args) -> error(self(), Format, Args). -spec error(pid() | [tuple()], string(), [any()]) -> 'ok'. error(Pid, Format, Args) -> - logger:error(Format, Args, #{pid => Pid, + ?LOG_ERROR(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_CONN}). -spec critical(string()) -> 'ok'. @@ -85,7 +86,7 @@ critical(Format, Args) -> critical(self(), Format, Args). -spec critical(pid() | [tuple()], string(), [any()]) -> 'ok'. critical(Pid, Format, Args) -> - logger:critical(Format, Args, #{pid => Pid, + ?LOG_CRITICAL(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_CONN}). -spec alert(string()) -> 'ok'. @@ -96,7 +97,7 @@ alert(Format, Args) -> alert(self(), Format, Args). -spec alert(pid() | [tuple()], string(), [any()]) -> 'ok'. alert(Pid, Format, Args) -> - logger:alert(Format, Args, #{pid => Pid, + ?LOG_ALERT(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_CONN}). -spec emergency(string()) -> 'ok'. @@ -107,7 +108,7 @@ emergency(Format, Args) -> emergency(self(), Format, Args). -spec emergency(pid() | [tuple()], string(), [any()]) -> 'ok'. emergency(Pid, Format, Args) -> - logger:emergency(Format, Args, #{pid => Pid, + ?LOG_EMERGENCY(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_CONN}). -spec none(string()) -> 'ok'. diff --git a/deps/rabbit/src/rabbit_log_mirroring.erl b/deps/rabbit/src/rabbit_log_mirroring.erl index 28d32dc9be48..fc4c0aef5841 100644 --- a/deps/rabbit/src/rabbit_log_mirroring.erl +++ b/deps/rabbit/src/rabbit_log_mirroring.erl @@ -19,6 +19,7 @@ none/1, none/2, none/3]). -include_lib("rabbit_common/include/logging.hrl"). +-include_lib("kernel/include/logger.hrl"). -compile({no_auto_import, [error/2, error/3]}). @@ -32,7 +33,7 @@ debug(Format, Args) -> debug(self(), Format, Args). -spec debug(pid() | [tuple()], string(), [any()]) -> 'ok'. debug(Pid, Format, Args) -> - logger:debug(Format, Args, #{pid => Pid, + ?LOG_DEBUG(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_MIRRORING}). -spec info(string()) -> 'ok'. @@ -43,7 +44,7 @@ info(Format, Args) -> info(self(), Format, Args). -spec info(pid() | [tuple()], string(), [any()]) -> 'ok'. info(Pid, Format, Args) -> - logger:info(Format, Args, #{pid => Pid, + ?LOG_INFO(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_MIRRORING}). -spec notice(string()) -> 'ok'. @@ -54,7 +55,7 @@ notice(Format, Args) -> notice(self(), Format, Args). -spec notice(pid() | [tuple()], string(), [any()]) -> 'ok'. notice(Pid, Format, Args) -> - logger:notice(Format, Args, #{pid => Pid, + ?LOG_NOTICE(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_MIRRORING}). -spec warning(string()) -> 'ok'. @@ -65,7 +66,7 @@ warning(Format, Args) -> warning(self(), Format, Args). -spec warning(pid() | [tuple()], string(), [any()]) -> 'ok'. warning(Pid, Format, Args) -> - logger:warning(Format, Args, #{pid => Pid, + ?LOG_WARNING(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_MIRRORING}). -spec error(string()) -> 'ok'. @@ -76,7 +77,7 @@ error(Format, Args) -> error(self(), Format, Args). -spec error(pid() | [tuple()], string(), [any()]) -> 'ok'. error(Pid, Format, Args) -> - logger:error(Format, Args, #{pid => Pid, + ?LOG_ERROR(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_MIRRORING}). -spec critical(string()) -> 'ok'. @@ -87,7 +88,7 @@ critical(Format, Args) -> critical(self(), Format, Args). -spec critical(pid() | [tuple()], string(), [any()]) -> 'ok'. critical(Pid, Format, Args) -> - logger:critical(Format, Args, #{pid => Pid, + ?LOG_CRITICAL(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_MIRRORING}). -spec alert(string()) -> 'ok'. @@ -98,7 +99,7 @@ alert(Format, Args) -> alert(self(), Format, Args). -spec alert(pid() | [tuple()], string(), [any()]) -> 'ok'. alert(Pid, Format, Args) -> - logger:alert(Format, Args, #{pid => Pid, + ?LOG_ALERT(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_MIRRORING}). -spec emergency(string()) -> 'ok'. @@ -109,7 +110,7 @@ emergency(Format, Args) -> emergency(self(), Format, Args). -spec emergency(pid() | [tuple()], string(), [any()]) -> 'ok'. emergency(Pid, Format, Args) -> - logger:emergency(Format, Args, #{pid => Pid, + ?LOG_EMERGENCY(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_MIRRORING}). -spec none(string()) -> 'ok'. diff --git a/deps/rabbit/src/rabbit_log_prelaunch.erl b/deps/rabbit/src/rabbit_log_prelaunch.erl index 47f05ca07998..0532dfbb97f7 100644 --- a/deps/rabbit/src/rabbit_log_prelaunch.erl +++ b/deps/rabbit/src/rabbit_log_prelaunch.erl @@ -19,6 +19,7 @@ none/1, none/2, none/3]). -include_lib("rabbit_common/include/logging.hrl"). +-include_lib("kernel/include/logger.hrl"). -compile({no_auto_import, [error/2, error/3]}). @@ -30,7 +31,7 @@ debug(Format, Args) -> debug(self(), Format, Args). -spec debug(pid() | [tuple()], string(), [any()]) -> 'ok'. debug(Pid, Format, Args) -> - logger:debug(Format, Args, #{pid => Pid, + ?LOG_DEBUG(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_PRELAUNCH}). -spec info(string()) -> 'ok'. @@ -41,7 +42,7 @@ info(Format, Args) -> info(self(), Format, Args). -spec info(pid() | [tuple()], string(), [any()]) -> 'ok'. info(Pid, Format, Args) -> - logger:info(Format, Args, #{pid => Pid, + ?LOG_INFO(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_PRELAUNCH}). -spec notice(string()) -> 'ok'. @@ -52,7 +53,7 @@ notice(Format, Args) -> notice(self(), Format, Args). -spec notice(pid() | [tuple()], string(), [any()]) -> 'ok'. notice(Pid, Format, Args) -> - logger:notice(Format, Args, #{pid => Pid, + ?LOG_NOTICE(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_PRELAUNCH}). -spec warning(string()) -> 'ok'. @@ -63,7 +64,7 @@ warning(Format, Args) -> warning(self(), Format, Args). -spec warning(pid() | [tuple()], string(), [any()]) -> 'ok'. warning(Pid, Format, Args) -> - logger:warning(Format, Args, #{pid => Pid, + ?LOG_WARNING(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_PRELAUNCH}). -spec error(string()) -> 'ok'. @@ -74,7 +75,7 @@ error(Format, Args) -> error(self(), Format, Args). -spec error(pid() | [tuple()], string(), [any()]) -> 'ok'. error(Pid, Format, Args) -> - logger:error(Format, Args, #{pid => Pid, + ?LOG_ERROR(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_PRELAUNCH}). -spec critical(string()) -> 'ok'. @@ -85,7 +86,7 @@ critical(Format, Args) -> critical(self(), Format, Args). -spec critical(pid() | [tuple()], string(), [any()]) -> 'ok'. critical(Pid, Format, Args) -> - logger:critical(Format, Args, #{pid => Pid, + ?LOG_CRITICAL(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_PRELAUNCH}). -spec alert(string()) -> 'ok'. @@ -96,7 +97,7 @@ alert(Format, Args) -> alert(self(), Format, Args). -spec alert(pid() | [tuple()], string(), [any()]) -> 'ok'. alert(Pid, Format, Args) -> - logger:alert(Format, Args, #{pid => Pid, + ?LOG_ALERT(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_PRELAUNCH}). -spec emergency(string()) -> 'ok'. @@ -107,7 +108,7 @@ emergency(Format, Args) -> emergency(self(), Format, Args). -spec emergency(pid() | [tuple()], string(), [any()]) -> 'ok'. emergency(Pid, Format, Args) -> - logger:emergency(Format, Args, #{pid => Pid, + ?LOG_EMERGENCY(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_PRELAUNCH}). -spec none(string()) -> 'ok'. diff --git a/deps/rabbit/src/rabbit_log_queue.erl b/deps/rabbit/src/rabbit_log_queue.erl index 1edb23dede02..a2c3315f6004 100644 --- a/deps/rabbit/src/rabbit_log_queue.erl +++ b/deps/rabbit/src/rabbit_log_queue.erl @@ -19,6 +19,7 @@ none/1, none/2, none/3]). -include_lib("rabbit_common/include/logging.hrl"). +-include_lib("kernel/include/logger.hrl"). -compile({no_auto_import, [error/2, error/3]}). @@ -30,7 +31,7 @@ debug(Format, Args) -> debug(self(), Format, Args). -spec debug(pid() | [tuple()], string(), [any()]) -> 'ok'. debug(Pid, Format, Args) -> - logger:debug(Format, Args, #{pid => Pid, + ?LOG_DEBUG(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_QUEUE}). -spec info(string()) -> 'ok'. @@ -41,7 +42,7 @@ info(Format, Args) -> info(self(), Format, Args). -spec info(pid() | [tuple()], string(), [any()]) -> 'ok'. info(Pid, Format, Args) -> - logger:info(Format, Args, #{pid => Pid, + ?LOG_INFO(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_QUEUE}). -spec notice(string()) -> 'ok'. @@ -52,7 +53,7 @@ notice(Format, Args) -> notice(self(), Format, Args). -spec notice(pid() | [tuple()], string(), [any()]) -> 'ok'. notice(Pid, Format, Args) -> - logger:notice(Format, Args, #{pid => Pid, + ?LOG_NOTICE(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_QUEUE}). -spec warning(string()) -> 'ok'. @@ -63,7 +64,7 @@ warning(Format, Args) -> warning(self(), Format, Args). -spec warning(pid() | [tuple()], string(), [any()]) -> 'ok'. warning(Pid, Format, Args) -> - logger:warning(Format, Args, #{pid => Pid, + ?LOG_WARNING(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_QUEUE}). -spec error(string()) -> 'ok'. @@ -74,7 +75,7 @@ error(Format, Args) -> error(self(), Format, Args). -spec error(pid() | [tuple()], string(), [any()]) -> 'ok'. error(Pid, Format, Args) -> - logger:error(Format, Args, #{pid => Pid, + ?LOG_ERROR(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_QUEUE}). -spec critical(string()) -> 'ok'. @@ -85,7 +86,7 @@ critical(Format, Args) -> critical(self(), Format, Args). -spec critical(pid() | [tuple()], string(), [any()]) -> 'ok'. critical(Pid, Format, Args) -> - logger:critical(Format, Args, #{pid => Pid, + ?LOG_CRITICAL(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_QUEUE}). -spec alert(string()) -> 'ok'. @@ -96,7 +97,7 @@ alert(Format, Args) -> alert(self(), Format, Args). -spec alert(pid() | [tuple()], string(), [any()]) -> 'ok'. alert(Pid, Format, Args) -> - logger:alert(Format, Args, #{pid => Pid, + ?LOG_ALERT(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_QUEUE}). -spec emergency(string()) -> 'ok'. @@ -107,7 +108,7 @@ emergency(Format, Args) -> emergency(self(), Format, Args). -spec emergency(pid() | [tuple()], string(), [any()]) -> 'ok'. emergency(Pid, Format, Args) -> - logger:emergency(Format, Args, #{pid => Pid, + ?LOG_EMERGENCY(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_QUEUE}). -spec none(string()) -> 'ok'. diff --git a/deps/rabbit/src/rabbit_node_monitor.erl b/deps/rabbit/src/rabbit_node_monitor.erl index 1fa3943e5eed..5939c156b259 100644 --- a/deps/rabbit/src/rabbit_node_monitor.erl +++ b/deps/rabbit/src/rabbit_node_monitor.erl @@ -317,7 +317,7 @@ find_blocked_global_peers() -> Snapshot1 = snapshot_global_dict(), timer:sleep(10_000), Snapshot2 = snapshot_global_dict(), - logger:debug("global's sync tags 10s ago: ~p~n" + ?LOG_DEBUG("global's sync tags 10s ago: ~p~n" "global's sync tags now: ~p", [Snapshot1, Snapshot2]), find_blocked_global_peers1(Snapshot2, Snapshot1). @@ -344,11 +344,11 @@ unblock_global_peer(PeerNode) -> PeerToThisCid = connection_id(PeerState, ThisNode), ThisToPeerCid = connection_id(ThisState, PeerNode), - logger:info( + ?LOG_INFO( "global hang workaround: faking nodedown / nodeup between peer node ~s " "(connection ID to us: ~p) and our node ~s (connection ID to peer: ~p)", [PeerNode, PeerToThisCid, ThisNode, ThisToPeerCid]), - logger:debug( + ?LOG_DEBUG( "peer global state: ~tp~nour global state: ~tp", [erpc:call(PeerNode, sys, get_status, [global_name_server]), sys:get_status(global_name_server)]), diff --git a/deps/rabbit/src/rabbit_time_travel_dbg.erl b/deps/rabbit/src/rabbit_time_travel_dbg.erl index 8787b4acd839..6c446bdc4c46 100644 --- a/deps/rabbit/src/rabbit_time_travel_dbg.erl +++ b/deps/rabbit/src/rabbit_time_travel_dbg.erl @@ -17,6 +17,9 @@ %% allowing you to easily figure out what happened. -module(rabbit_time_travel_dbg). + +-include_lib("kernel/include/logger.hrl"). + -compile(export_all). -compile(nowarn_export_all). @@ -62,7 +65,7 @@ loop(Q) -> [io_lib:format("~0p~n", [E]) || E <- queue:to_list(Q)]), loop(Q); print -> - _ = [logger:error("~0p", [E]) || E <- queue:to_list(Q)], + _ = [?LOG_ERROR("~0p", [E]) || E <- queue:to_list(Q)], loop(Q); stop -> ok; diff --git a/deps/rabbit/src/tcp_listener.erl b/deps/rabbit/src/tcp_listener.erl index 8e491f9e8695..ccec4fc23940 100644 --- a/deps/rabbit/src/tcp_listener.erl +++ b/deps/rabbit/src/tcp_listener.erl @@ -7,6 +7,9 @@ -module(tcp_listener). +-include_lib("kernel/include/logger.hrl"). + + %% Represents a running TCP listener (a process that listens for inbound %% TCP or TLS connections). Every protocol supported typically has one %% or two listeners, plain TCP and (optionally) TLS, but there can @@ -65,7 +68,7 @@ start_link(IPAddress, Port, init({IPAddress, Port, {M, F, A}, OnShutdown, Label}) -> process_flag(trap_exit, true), - logger:info("started ~ts on ~ts:~tp", [Label, rabbit_misc:ntoab(IPAddress), Port]), + ?LOG_INFO("started ~ts on ~ts:~tp", [Label, rabbit_misc:ntoab(IPAddress), Port]), apply(M, F, A ++ [IPAddress, Port]), State0 = #state{ on_shutdown = OnShutdown, @@ -85,11 +88,11 @@ handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, #state{on_shutdown = OnShutdown, label = Label, ip = IPAddress, port = Port}) -> - logger:info("stopped ~ts on ~ts:~tp", [Label, rabbit_misc:ntoab(IPAddress), Port]), + ?LOG_INFO("stopped ~ts on ~ts:~tp", [Label, rabbit_misc:ntoab(IPAddress), Port]), try OnShutdown(IPAddress, Port) catch _:Error -> - logger:error("Failed to stop ~ts on ~ts:~tp: ~tp", + ?LOG_ERROR("Failed to stop ~ts on ~ts:~tp: ~tp", [Label, rabbit_misc:ntoab(IPAddress), Port, Error]) end. diff --git a/deps/rabbit/test/classic_queue_prop_SUITE.erl b/deps/rabbit/test/classic_queue_prop_SUITE.erl index cf4cee4c3bc3..708127e3164a 100644 --- a/deps/rabbit/test/classic_queue_prop_SUITE.erl +++ b/deps/rabbit/test/classic_queue_prop_SUITE.erl @@ -12,13 +12,14 @@ %% Set to true to get an awful lot of debug logs. -if(false). --define(DEBUG(X,Y), logger:debug("~0p: " ++ X, [?FUNCTION_NAME|Y])). +-define(DEBUG(X,Y), ?LOG_DEBUG("~0p: " ++ X, [?FUNCTION_NAME|Y])). -else. -define(DEBUG(X,Y), _ = X, _ = Y, ok). -endif. -include_lib("amqp_client/include/amqp_client.hrl"). -include_lib("proper/include/proper.hrl"). +-include_lib("kernel/include/logger.hrl"). -record(cq, { amq = undefined :: amqqueue:amqqueue(), @@ -202,7 +203,7 @@ on_output_fun() -> fun (".", _) -> ok; % don't print the '.'s on new lines ("!", _) -> ok; ("~n", _) -> ok; % don't print empty lines; CT adds many to logs already - ("~w~n", A) -> logger:error("~tp~n", [A]); % make sure this gets sent to the terminal, it's important + ("~w~n", A) -> ?LOG_ERROR("~tp~n", [A]); % make sure this gets sent to the terminal, it's important (F, A) -> io:format(F, A) end. @@ -220,7 +221,7 @@ prop_common(InitialState) -> ?TRAPEXIT(begin {History, State, Result} = run_commands(?MODULE, Commands), cmd_teardown_queue(State), - ?WHENFAIL(logger:error("History: ~tp~nState: ~tp~nResult: ~tp", + ?WHENFAIL(?LOG_ERROR("History: ~tp~nState: ~tp~nResult: ~tp", [History, State, Result]), aggregate(command_names(Commands), Result =:= ok)) end) diff --git a/deps/rabbit/test/logging_SUITE.erl b/deps/rabbit/test/logging_SUITE.erl index 5e89034a51d5..abd374ec01ee 100644 --- a/deps/rabbit/test/logging_SUITE.erl +++ b/deps/rabbit/test/logging_SUITE.erl @@ -1300,7 +1300,7 @@ log_and_return_line(Context, Metadata) -> 32, "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"), - logger:warning(RandomMsg, Metadata), + ?LOG_WARNING(RandomMsg, Metadata), rabbit_logger_std_h:filesync(rmq_1_file_1), MainFile = main_log_file_in_context(Context), diff --git a/deps/rabbit_common/src/rabbit_env.erl b/deps/rabbit_common/src/rabbit_env.erl index 49f4ad0a5e1e..e3c551ae9c01 100644 --- a/deps/rabbit_common/src/rabbit_env.erl +++ b/deps/rabbit_common/src/rabbit_env.erl @@ -2109,7 +2109,7 @@ setup_dist_for_remote_query(#{from_remote_node := {Remote, _}} = Context, {error, {{already_started, _}, _}} -> Context; Error -> - logger:error( + ?LOG_ERROR( "rabbit_env: Failed to setup distribution (as ~ts) to " "query node ~ts: ~tp", [Nodename, Remote, Error]), diff --git a/deps/rabbitmq_auth_backend_ldap/src/rabbit_log_ldap.erl b/deps/rabbitmq_auth_backend_ldap/src/rabbit_log_ldap.erl index 330057fc74bd..fe63a9bb23cd 100644 --- a/deps/rabbitmq_auth_backend_ldap/src/rabbit_log_ldap.erl +++ b/deps/rabbitmq_auth_backend_ldap/src/rabbit_log_ldap.erl @@ -19,6 +19,7 @@ none/1, none/2, none/3]). -include("logging.hrl"). +-include_lib("kernel/include/logger.hrl"). -compile({no_auto_import, [error/2, error/3]}). @@ -57,49 +58,49 @@ debug(Format) -> debug(Format, []). debug(Format, Args) -> debug(self(), Format, Args). debug(Pid, Format, Args) -> - logger:debug(Format, Args, #{pid => Pid, + ?LOG_DEBUG(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_LDAP}). info(Format) -> info(Format, []). info(Format, Args) -> info(self(), Format, Args). info(Pid, Format, Args) -> - logger:info(Format, Args, #{pid => Pid, + ?LOG_INFO(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_LDAP}). notice(Format) -> notice(Format, []). notice(Format, Args) -> notice(self(), Format, Args). notice(Pid, Format, Args) -> - logger:notice(Format, Args, #{pid => Pid, + ?LOG_NOTICE(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_LDAP}). warning(Format) -> warning(Format, []). warning(Format, Args) -> warning(self(), Format, Args). warning(Pid, Format, Args) -> - logger:warning(Format, Args, #{pid => Pid, + ?LOG_WARNING(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_LDAP}). error(Format) -> error(Format, []). error(Format, Args) -> error(self(), Format, Args). error(Pid, Format, Args) -> - logger:error(Format, Args, #{pid => Pid, + ?LOG_ERROR(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_LDAP}). critical(Format) -> critical(Format, []). critical(Format, Args) -> critical(self(), Format, Args). critical(Pid, Format, Args) -> - logger:critical(Format, Args, #{pid => Pid, + ?LOG_CRITICAL(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_LDAP}). alert(Format) -> alert(Format, []). alert(Format, Args) -> alert(self(), Format, Args). alert(Pid, Format, Args) -> - logger:alert(Format, Args, #{pid => Pid, + ?LOG_ALERT(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_LDAP}). emergency(Format) -> emergency(Format, []). emergency(Format, Args) -> emergency(self(), Format, Args). emergency(Pid, Format, Args) -> - logger:emergency(Format, Args, #{pid => Pid, + ?LOG_EMERGENCY(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_LDAP}). none(_Format) -> ok. diff --git a/deps/rabbitmq_auth_backend_oauth2/src/uaa_jwt_jwk.erl b/deps/rabbitmq_auth_backend_oauth2/src/uaa_jwt_jwk.erl index 569b4f576a5f..2fe4bb211ec1 100644 --- a/deps/rabbitmq_auth_backend_oauth2/src/uaa_jwt_jwk.erl +++ b/deps/rabbitmq_auth_backend_oauth2/src/uaa_jwt_jwk.erl @@ -9,6 +9,7 @@ -export([make_jwk/1, from_pem/1, from_pem_file/1]). -include_lib("jose/include/jose_jwk.hrl"). +-include_lib("kernel/include/logger.hrl"). -spec make_jwk(binary() | map()) -> {ok, #{binary() => binary()}} | {error, term()}. make_jwk(Json) when is_binary(Json); is_list(Json) -> @@ -43,7 +44,7 @@ from_pem(Pem) -> case jose_jwk:from_pem(Pem) of #jose_jwk{} = Jwk -> {ok, Jwk}; Other -> - error_logger:warning_msg("Error parsing jwk from pem: ", [Other]), + ?LOG_WARNING("Error parsing jwk from pem: ", [Other]), {error, invalid_pem_string} end. @@ -55,7 +56,7 @@ from_pem_file(FileName) -> case jose_jwk:from_pem_file(FileName) of #jose_jwk{} = Jwk -> {ok, Jwk}; Other -> - error_logger:warning_msg("Error parsing jwk from pem file: ", [Other]), + ?LOG_WARNING("Error parsing jwk from pem file: ", [Other]), {error, invalid_pem_file} end end. diff --git a/deps/rabbitmq_aws/src/rabbitmq_aws.erl b/deps/rabbitmq_aws/src/rabbitmq_aws.erl index 04b6993f89c3..5a45a597d851 100644 --- a/deps/rabbitmq_aws/src/rabbitmq_aws.erl +++ b/deps/rabbitmq_aws/src/rabbitmq_aws.erl @@ -335,7 +335,7 @@ load_credentials(#state{region = Region}) -> security_token = SecurityToken, imdsv2_token = undefined}}; {error, Reason} -> - error_logger:error_msg("Could not load AWS credentials from environment variables, AWS_CONFIG_FILE, AWS_SHARED_CREDENTIALS_FILE or EC2 metadata endpoint: ~tp. Will depend on config settings to be set~n", [Reason]), + ?LOG_ERROR("Could not load AWS credentials from environment variables, AWS_CONFIG_FILE, AWS_SHARED_CREDENTIALS_FILE or EC2 metadata endpoint: ~tp. Will depend on config settings to be set~n", [Reason]), {error, #state{region = Region, error = Reason, access_key = undefined, diff --git a/deps/rabbitmq_federation_common/src/rabbit_federation_pg.erl b/deps/rabbitmq_federation_common/src/rabbit_federation_pg.erl index 32ec7cbe959e..7fe1eb612b23 100644 --- a/deps/rabbitmq_federation_common/src/rabbit_federation_pg.erl +++ b/deps/rabbitmq_federation_common/src/rabbit_federation_pg.erl @@ -7,6 +7,9 @@ -module(rabbit_federation_pg). +-include_lib("kernel/include/logger.hrl"). + + -export([start_scope/1, stop_scope/1]). start_scope(Scope) -> @@ -38,7 +41,7 @@ stop_group(Scope, Group) -> fun(MRef) -> receive {'DOWN', MRef, process, _Member, _Info} -> - logger:alert("Member ~p stopped: ~0p", [_Member, _Info]), + ?LOG_ALERT("Member ~p stopped: ~0p", [_Member, _Info]), ok end end, MRefs), diff --git a/deps/rabbitmq_federation_common/src/rabbit_log_federation.erl b/deps/rabbitmq_federation_common/src/rabbit_log_federation.erl index 3b7c80d412f4..1704935ee273 100644 --- a/deps/rabbitmq_federation_common/src/rabbit_log_federation.erl +++ b/deps/rabbitmq_federation_common/src/rabbit_log_federation.erl @@ -19,6 +19,7 @@ none/1, none/2, none/3]). -include("logging.hrl"). +-include_lib("kernel/include/logger.hrl"). -compile({no_auto_import, [error/2, error/3]}). @@ -57,49 +58,49 @@ debug(Format) -> debug(Format, []). debug(Format, Args) -> debug(self(), Format, Args). debug(Pid, Format, Args) -> - logger:debug(Format, Args, #{pid => Pid, + ?LOG_DEBUG(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_FEDERATION}). info(Format) -> info(Format, []). info(Format, Args) -> info(self(), Format, Args). info(Pid, Format, Args) -> - logger:info(Format, Args, #{pid => Pid, + ?LOG_INFO(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_FEDERATION}). notice(Format) -> notice(Format, []). notice(Format, Args) -> notice(self(), Format, Args). notice(Pid, Format, Args) -> - logger:notice(Format, Args, #{pid => Pid, + ?LOG_NOTICE(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_FEDERATION}). warning(Format) -> warning(Format, []). warning(Format, Args) -> warning(self(), Format, Args). warning(Pid, Format, Args) -> - logger:warning(Format, Args, #{pid => Pid, + ?LOG_WARNING(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_FEDERATION}). error(Format) -> error(Format, []). error(Format, Args) -> error(self(), Format, Args). error(Pid, Format, Args) -> - logger:error(Format, Args, #{pid => Pid, + ?LOG_ERROR(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_FEDERATION}). critical(Format) -> critical(Format, []). critical(Format, Args) -> critical(self(), Format, Args). critical(Pid, Format, Args) -> - logger:critical(Format, Args, #{pid => Pid, + ?LOG_CRITICAL(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_FEDERATION}). alert(Format) -> alert(Format, []). alert(Format, Args) -> alert(self(), Format, Args). alert(Pid, Format, Args) -> - logger:alert(Format, Args, #{pid => Pid, + ?LOG_ALERT(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_FEDERATION}). emergency(Format) -> emergency(Format, []). emergency(Format, Args) -> emergency(self(), Format, Args). emergency(Pid, Format, Args) -> - logger:emergency(Format, Args, #{pid => Pid, + ?LOG_EMERGENCY(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_FEDERATION}). none(_Format) -> ok. diff --git a/deps/rabbitmq_prelaunch/src/rabbit_prelaunch_sighandler.erl b/deps/rabbitmq_prelaunch/src/rabbit_prelaunch_sighandler.erl index 3da0109d9839..14b02b1a9d8a 100644 --- a/deps/rabbitmq_prelaunch/src/rabbit_prelaunch_sighandler.erl +++ b/deps/rabbitmq_prelaunch/src/rabbit_prelaunch_sighandler.erl @@ -1,4 +1,7 @@ -module(rabbit_prelaunch_sighandler). + +-include_lib("kernel/include/logger.hrl"). + -behaviour(gen_event). -export([setup/0, @@ -69,12 +72,12 @@ handle_event(Signal, State) -> %% which should stop RabbitMQ. % %#{Signal := stop} -> - % logger:info( + % ?LOG_INFO( % "~ts received - shutting down", % [string:uppercase(atom_to_list(Signal))]), % ok = init:stop(); _ -> - logger:info( + ?LOG_INFO( "~ts received - unhandled signal", [string:uppercase(atom_to_list(Signal))]) end, diff --git a/deps/rabbitmq_shovel/src/rabbit_log_shovel.erl b/deps/rabbitmq_shovel/src/rabbit_log_shovel.erl index 4238e3491d6d..5aa644defc64 100644 --- a/deps/rabbitmq_shovel/src/rabbit_log_shovel.erl +++ b/deps/rabbitmq_shovel/src/rabbit_log_shovel.erl @@ -19,6 +19,7 @@ none/1, none/2, none/3]). -include("logging.hrl"). +-include_lib("kernel/include/logger.hrl"). -compile({no_auto_import, [error/2, error/3]}). @@ -57,49 +58,49 @@ debug(Format) -> debug(Format, []). debug(Format, Args) -> debug(self(), Format, Args). debug(Pid, Format, Args) -> - logger:debug(Format, Args, #{pid => Pid, + ?LOG_DEBUG(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_SHOVEL}). info(Format) -> info(Format, []). info(Format, Args) -> info(self(), Format, Args). info(Pid, Format, Args) -> - logger:info(Format, Args, #{pid => Pid, + ?LOG_INFO(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_SHOVEL}). notice(Format) -> notice(Format, []). notice(Format, Args) -> notice(self(), Format, Args). notice(Pid, Format, Args) -> - logger:notice(Format, Args, #{pid => Pid, + ?LOG_NOTICE(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_SHOVEL}). warning(Format) -> warning(Format, []). warning(Format, Args) -> warning(self(), Format, Args). warning(Pid, Format, Args) -> - logger:warning(Format, Args, #{pid => Pid, + ?LOG_WARNING(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_SHOVEL}). error(Format) -> error(Format, []). error(Format, Args) -> error(self(), Format, Args). error(Pid, Format, Args) -> - logger:error(Format, Args, #{pid => Pid, + ?LOG_ERROR(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_SHOVEL}). critical(Format) -> critical(Format, []). critical(Format, Args) -> critical(self(), Format, Args). critical(Pid, Format, Args) -> - logger:critical(Format, Args, #{pid => Pid, + ?LOG_CRITICAL(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_SHOVEL}). alert(Format) -> alert(Format, []). alert(Format, Args) -> alert(self(), Format, Args). alert(Pid, Format, Args) -> - logger:alert(Format, Args, #{pid => Pid, + ?LOG_ALERT(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_SHOVEL}). emergency(Format) -> emergency(Format, []). emergency(Format, Args) -> emergency(self(), Format, Args). emergency(Pid, Format, Args) -> - logger:emergency(Format, Args, #{pid => Pid, + ?LOG_EMERGENCY(Format, Args, #{pid => Pid, domain => ?RMQLOG_DOMAIN_SHOVEL}). none(_Format) -> ok. diff --git a/deps/rabbitmq_stream_common/src/rabbit_stream_core.erl b/deps/rabbitmq_stream_common/src/rabbit_stream_core.erl index fad066a2df0f..bba485db9d5f 100644 --- a/deps/rabbitmq_stream_common/src/rabbit_stream_core.erl +++ b/deps/rabbitmq_stream_common/src/rabbit_stream_core.erl @@ -17,6 +17,7 @@ -module(rabbit_stream_core). -include("rabbit_stream.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([init/1, incoming_data/2, @@ -778,7 +779,7 @@ parse_request(<> -> parse_map(Bin, #{}); _ -> - logger:warning("Incorrect binary for subscription properties: ~w", + ?LOG_WARNING("Incorrect binary for subscription properties: ~w", [PropsBin]), #{} end, diff --git a/deps/rabbitmq_web_dispatch/src/webmachine_log.erl b/deps/rabbitmq_web_dispatch/src/webmachine_log.erl index 9c6af6f15467..2c17626a0595 100644 --- a/deps/rabbitmq_web_dispatch/src/webmachine_log.erl +++ b/deps/rabbitmq_web_dispatch/src/webmachine_log.erl @@ -19,6 +19,7 @@ -module(webmachine_log). -include("webmachine_logger.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([add_handler/2, call/2, @@ -135,7 +136,7 @@ log_access({_, _, _}=LogData) -> %% @doc Close a log file. -spec log_close(atom(), string(), file:io_device()) -> ok | {error, term()}. log_close(Mod, Name, FD) -> - logger:info("~tp: closing log file: ~tp", [Mod, Name]), + ?LOG_INFO("~tp: closing log file: ~tp", [Mod, Name]), file:close(FD). %% @doc Open a new log file for writing @@ -148,7 +149,7 @@ log_open(FileName) -> -spec log_open(string(), datehour()) -> file:io_device(). log_open(FileName, DateHour) -> LogName = FileName ++ suffix(DateHour), - logger:info("opening log file: ~tp", [LogName]), + ?LOG_INFO("opening log file: ~tp", [LogName]), _ = filelib:ensure_dir(LogName), {ok, FD} = file:open(LogName, [read, write, raw]), {ok, Location} = file:position(FD, eof), diff --git a/deps/trust_store_http/src/trust_store_list_handler.erl b/deps/trust_store_http/src/trust_store_list_handler.erl index 416dfc253d99..e8b687d1a908 100644 --- a/deps/trust_store_http/src/trust_store_list_handler.erl +++ b/deps/trust_store_http/src/trust_store_list_handler.erl @@ -2,6 +2,7 @@ -behaviour(cowboy_handler). -include_lib("kernel/include/file.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([init/2]). -export([terminate/3]). @@ -24,7 +25,7 @@ respond(Files, Req, State) -> respond_error(Reason, Req, State) -> Error = io_lib:format("Error listing certificates ~tp", [Reason]), - logger:log(error, "~ts", [Error]), + ?LOG_ERROR("~ts", [Error]), Req2 = cowboy_req:reply(500, #{}, iolist_to_binary(Error), Req), {ok, Req2, State}. From 14fc15a0c28376859a9abee013e3d415d6cf8f83 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Fri, 11 Jul 2025 13:23:30 +0200 Subject: [PATCH 03/31] [skip ci] Remove rabbit_log_queue, replace with LOG_ macros --- deps/rabbit/src/rabbit_amqqueue_process.erl | 21 +-- deps/rabbit/src/rabbit_log_queue.erl | 121 ------------------ .../src/rabbit_mqtt_qos0_queue.erl | 6 +- 3 files changed, 17 insertions(+), 131 deletions(-) delete mode 100644 deps/rabbit/src/rabbit_log_queue.erl diff --git a/deps/rabbit/src/rabbit_amqqueue_process.erl b/deps/rabbit/src/rabbit_amqqueue_process.erl index 1ad36a3cdd67..aca2d9b6cbe8 100644 --- a/deps/rabbit/src/rabbit_amqqueue_process.erl +++ b/deps/rabbit/src/rabbit_amqqueue_process.erl @@ -9,6 +9,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include("amqqueue.hrl"). -include_lib("kernel/include/logger.hrl"). +-include_lib("rabbit_common/include/logging.hrl"). -behaviour(gen_server2). @@ -143,6 +144,8 @@ start_link(Q, Marker) -> gen_server2:start_link(?MODULE, {Q, Marker}, []). init({Q, Marker}) -> + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_QUEUE, + pid => self()}), case is_process_alive(Marker) of true -> %% start @@ -1605,7 +1608,8 @@ handle_cast({force_event_refresh, Ref}, rabbit_event:notify(queue_created, queue_created_infos(State), Ref), QName = qname(State), AllConsumers = rabbit_queue_consumers:all(Consumers), - ?LOG_DEBUG("Queue ~ts forced to re-emit events, consumers: ~tp", [rabbit_misc:rs(QName), AllConsumers]), + ?LOG_DEBUG("Queue ~ts forced to re-emit events, consumers: ~tp", + [rabbit_misc:rs(QName), AllConsumers]), [emit_consumer_created( Ch, CTag, ActiveOrExclusive, AckRequired, QName, Prefetch, Args, Ref, ActingUser) || @@ -1650,7 +1654,8 @@ handle_info({maybe_expire, Vsn}, State = #q{q = Q, expires = Expiry, args_policy case is_unused(State) of true -> QResource = rabbit_misc:rs(amqqueue:get_name(Q)), - rabbit_log_queue:debug("Deleting 'classic ~ts' on expiry after ~tp milliseconds", [QResource, Expiry]), + ?LOG_DEBUG("Deleting 'classic ~ts' on expiry after ~tp milliseconds", + [QResource, Expiry]), stop(State); false -> noreply(State#q{expiry_timer_ref = undefined}) end; @@ -1752,16 +1757,16 @@ log_delete_exclusive({ConPid, _ConRef}, State) -> log_delete_exclusive(ConPid, #q{ q = Q }) -> Resource = amqqueue:get_name(Q), #resource{ name = QName, virtual_host = VHost } = Resource, - rabbit_log_queue:debug("Deleting exclusive queue '~ts' in vhost '~ts' " ++ - "because its declaring connection ~tp was closed", - [QName, VHost, ConPid]). + ?LOG_DEBUG("Deleting exclusive queue '~ts' in vhost '~ts' " ++ + "because its declaring connection ~tp was closed", + [QName, VHost, ConPid]). log_auto_delete(Reason, #q{ q = Q }) -> Resource = amqqueue:get_name(Q), #resource{ name = QName, virtual_host = VHost } = Resource, - rabbit_log_queue:debug("Deleting auto-delete queue '~ts' in vhost '~ts' " ++ - Reason, - [QName, VHost]). + ?LOG_DEBUG("Deleting auto-delete queue '~ts' in vhost '~ts' " ++ + Reason, + [QName, VHost]). confirm_to_sender(Pid, QName, MsgSeqNos) -> rabbit_classic_queue:confirm_to_sender(Pid, QName, MsgSeqNos). diff --git a/deps/rabbit/src/rabbit_log_queue.erl b/deps/rabbit/src/rabbit_log_queue.erl deleted file mode 100644 index a2c3315f6004..000000000000 --- a/deps/rabbit/src/rabbit_log_queue.erl +++ /dev/null @@ -1,121 +0,0 @@ -%% This Source Code Form is subject to the terms of the Mozilla Public -%% License, v. 2.0. If a copy of the MPL was not distributed with this -%% file, You can obtain one at https://mozilla.org/MPL/2.0/. -%% -%% Copyright (c) 2007-2025 Broadcom. All Rights Reserved. The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. All rights reserved. -%% - -%% @doc Compatibility module for the old Lager-based logging API. --module(rabbit_log_queue). - --export([debug/1, debug/2, debug/3, - info/1, info/2, info/3, - notice/1, notice/2, notice/3, - warning/1, warning/2, warning/3, - error/1, error/2, error/3, - critical/1, critical/2, critical/3, - alert/1, alert/2, alert/3, - emergency/1, emergency/2, emergency/3, - none/1, none/2, none/3]). - --include_lib("rabbit_common/include/logging.hrl"). --include_lib("kernel/include/logger.hrl"). - --compile({no_auto_import, [error/2, error/3]}). - --spec debug(string()) -> 'ok'. -debug(Format) -> debug(Format, []). - --spec debug(string(), [any()]) -> 'ok'. -debug(Format, Args) -> debug(self(), Format, Args). - --spec debug(pid() | [tuple()], string(), [any()]) -> 'ok'. -debug(Pid, Format, Args) -> - ?LOG_DEBUG(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_QUEUE}). - --spec info(string()) -> 'ok'. -info(Format) -> info(Format, []). - --spec info(string(), [any()]) -> 'ok'. -info(Format, Args) -> info(self(), Format, Args). - --spec info(pid() | [tuple()], string(), [any()]) -> 'ok'. -info(Pid, Format, Args) -> - ?LOG_INFO(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_QUEUE}). - --spec notice(string()) -> 'ok'. -notice(Format) -> notice(Format, []). - --spec notice(string(), [any()]) -> 'ok'. -notice(Format, Args) -> notice(self(), Format, Args). - --spec notice(pid() | [tuple()], string(), [any()]) -> 'ok'. -notice(Pid, Format, Args) -> - ?LOG_NOTICE(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_QUEUE}). - --spec warning(string()) -> 'ok'. -warning(Format) -> warning(Format, []). - --spec warning(string(), [any()]) -> 'ok'. -warning(Format, Args) -> warning(self(), Format, Args). - --spec warning(pid() | [tuple()], string(), [any()]) -> 'ok'. -warning(Pid, Format, Args) -> - ?LOG_WARNING(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_QUEUE}). - --spec error(string()) -> 'ok'. -error(Format) -> error(Format, []). - --spec error(string(), [any()]) -> 'ok'. -error(Format, Args) -> error(self(), Format, Args). - --spec error(pid() | [tuple()], string(), [any()]) -> 'ok'. -error(Pid, Format, Args) -> - ?LOG_ERROR(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_QUEUE}). - --spec critical(string()) -> 'ok'. -critical(Format) -> critical(Format, []). - --spec critical(string(), [any()]) -> 'ok'. -critical(Format, Args) -> critical(self(), Format, Args). - --spec critical(pid() | [tuple()], string(), [any()]) -> 'ok'. -critical(Pid, Format, Args) -> - ?LOG_CRITICAL(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_QUEUE}). - --spec alert(string()) -> 'ok'. -alert(Format) -> alert(Format, []). - --spec alert(string(), [any()]) -> 'ok'. -alert(Format, Args) -> alert(self(), Format, Args). - --spec alert(pid() | [tuple()], string(), [any()]) -> 'ok'. -alert(Pid, Format, Args) -> - ?LOG_ALERT(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_QUEUE}). - --spec emergency(string()) -> 'ok'. -emergency(Format) -> emergency(Format, []). - --spec emergency(string(), [any()]) -> 'ok'. -emergency(Format, Args) -> emergency(self(), Format, Args). - --spec emergency(pid() | [tuple()], string(), [any()]) -> 'ok'. -emergency(Pid, Format, Args) -> - ?LOG_EMERGENCY(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_QUEUE}). - --spec none(string()) -> 'ok'. -none(_Format) -> ok. - --spec none(string(), [any()]) -> 'ok'. -none(_Format, _Args) -> ok. - --spec none(pid() | [tuple()], string(), [any()]) -> 'ok'. -none(_Pid, _Format, _Args) -> ok. diff --git a/deps/rabbitmq_mqtt/src/rabbit_mqtt_qos0_queue.erl b/deps/rabbitmq_mqtt/src/rabbit_mqtt_qos0_queue.erl index a9311381ffa6..3407a238a930 100644 --- a/deps/rabbitmq_mqtt/src/rabbit_mqtt_qos0_queue.erl +++ b/deps/rabbitmq_mqtt/src/rabbit_mqtt_qos0_queue.erl @@ -21,6 +21,8 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include_lib("rabbit/include/amqqueue.hrl"). +-include_lib("rabbit_common/include/logging.hrl"). +-include_lib("kernel/include/logger.hrl"). %% Stateless rabbit_queue_type callbacks. -export([ @@ -205,8 +207,8 @@ recover(_VHost, Queues) -> {[], Queues}. log_delete(QName, ConPid) -> - rabbit_log_queue:debug("Deleting ~s of type ~s because its declaring connection ~tp was closed", - [rabbit_misc:rs(QName), ?MODULE, ConPid]). + ?LOG_DEBUG("Deleting ~s of type ~s because its declaring connection ~tp was closed", + [rabbit_misc:rs(QName), ?MODULE, ConPid], #{domain => ?RMQLOG_DOMAIN_QUEUE}). -spec purge(amqqueue:amqqueue()) -> {ok, non_neg_integer()}. From 1743881fe1a178e6df05bfb37d6e03bc4d0bc136 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Fri, 11 Jul 2025 13:34:11 +0200 Subject: [PATCH 04/31] [skip ci] Remove rabbit_log_channel and use LOG_ macros directly --- deps/rabbit/src/rabbit_channel.erl | 24 ++-- deps/rabbit/src/rabbit_channel_tracking.erl | 13 ++- deps/rabbit/src/rabbit_log_channel.erl | 121 -------------------- 3 files changed, 23 insertions(+), 135 deletions(-) delete mode 100644 deps/rabbit/src/rabbit_log_channel.erl diff --git a/deps/rabbit/src/rabbit_channel.erl b/deps/rabbit/src/rabbit_channel.erl index 0e6a2a74d221..7248bf906f34 100644 --- a/deps/rabbit/src/rabbit_channel.erl +++ b/deps/rabbit/src/rabbit_channel.erl @@ -41,6 +41,8 @@ -include_lib("rabbit_common/include/rabbit_framing.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). -include_lib("rabbit_common/include/rabbit_misc.hrl"). +-include_lib("rabbit_common/include/logging.hrl"). +-include_lib("kernel/include/logger.hrl"). -include("amqqueue.hrl"). @@ -465,6 +467,8 @@ init([Channel, ReaderPid, WriterPid, ConnPid, ConnName, Protocol, User, VHost, Capabilities, CollectorPid, LimiterPid, AmqpParams]) -> process_flag(trap_exit, true), rabbit_process_flag:adjust_for_message_handling_proc(), + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_CHAN, + pid => self()}), ?LG_PROCESS_TYPE(channel), ?store_proc_name({ConnName, Channel}), @@ -749,8 +753,8 @@ handle_info({'EXIT', _Pid, Reason}, State) -> handle_info({{Ref, Node}, LateAnswer}, State = #ch{cfg = #conf{channel = Channel}}) when is_reference(Ref) -> - rabbit_log_channel:warning("Channel ~tp ignoring late answer ~tp from ~tp", - [Channel, LateAnswer, Node]), + ?LOG_WARNING("Channel ~tp ignoring late answer ~tp from ~tp", + [Channel, LateAnswer, Node]), noreply(State); handle_info(tick, State0 = #ch{queue_states = QueueStates0}) -> @@ -866,7 +870,7 @@ handle_exception(Reason, State = #ch{cfg = #conf{protocol = Protocol, {_Result, State1} = notify_queues(State), case rabbit_binary_generator:map_exception(Channel, Reason, Protocol) of {Channel, CloseMethod} -> - rabbit_log_channel:error( + ?LOG_ERROR( "Channel error on connection ~tp (~ts, vhost: '~ts'," " user: '~ts'), channel ~tp:~n~ts", [ConnPid, ConnName, VHost, User#user.username, @@ -2719,13 +2723,13 @@ evaluate_consumer_timeout1(PA = #pending_ack{delivered_at = Time}, handle_consumer_timed_out(Timeout,#pending_ack{delivery_tag = DeliveryTag, tag = ConsumerTag, queue = QName}, State = #ch{cfg = #conf{channel = Channel}}) -> - rabbit_log_channel:warning("Consumer '~ts' on channel ~w and ~ts has timed out " - "waiting for a consumer acknowledgement of a delivery with delivery tag = ~b. Timeout used: ~tp ms. " - "This timeout value can be configured, see consumers doc guide to learn more", - [ConsumerTag, - Channel, - rabbit_misc:rs(QName), - DeliveryTag, Timeout]), + ?LOG_WARNING("Consumer '~ts' on channel ~w and ~ts has timed out " + "waiting for a consumer acknowledgement of a delivery with delivery tag = ~b. Timeout used: ~tp ms. " + "This timeout value can be configured, see consumers doc guide to learn more", + [ConsumerTag, + Channel, + rabbit_misc:rs(QName), + DeliveryTag, Timeout]), Ex = rabbit_misc:amqp_error(precondition_failed, "delivery acknowledgement on channel ~w timed out. " "Timeout value used: ~tp ms. " diff --git a/deps/rabbit/src/rabbit_channel_tracking.erl b/deps/rabbit/src/rabbit_channel_tracking.erl index 63595452d3cd..b3bbbf2e45d5 100644 --- a/deps/rabbit/src/rabbit_channel_tracking.erl +++ b/deps/rabbit/src/rabbit_channel_tracking.erl @@ -35,6 +35,8 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include_lib("kernel/include/logger.hrl"). +-include_lib("rabbit_common/include/logging.hrl"). + -import(rabbit_misc, [pget/2]). @@ -66,11 +68,13 @@ handle_cast({channel_created, Details}) -> error:{no_exists, _} -> Msg = "Could not register channel ~tp for tracking, " "its table is not ready yet or the channel terminated prematurely", - rabbit_log_connection:warning(Msg, [TrackedChId]), + ?LOG_WARNING(Msg, [TrackedChId], #{domain => ?RMQLOG_DOMAIN_CHAN, + pid => self()}), ok; error:Err -> Msg = "Could not register channel ~tp for tracking: ~tp", - rabbit_log_connection:warning(Msg, [TrackedChId, Err]), + ?LOG_WARNING(Msg, [TrackedChId, Err], #{domain => ?RMQLOG_DOMAIN_CHAN, + pid => self()}), ok end; _OtherNode -> @@ -89,9 +93,10 @@ handle_cast({connection_closed, ConnDetails}) -> [] -> ok; TrackedChs -> - rabbit_log_channel:debug( + ?LOG_DEBUG( "Closing ~b channel(s) because connection '~ts' has been closed", - [length(TrackedChs), pget(name, ConnDetails)]), + [length(TrackedChs), pget(name, ConnDetails)], + #{domain => ?RMQLOG_DOMAIN_CHAN, pid => self()}), %% Shutting down channels will take care of unregistering the %% corresponding tracking. shutdown_tracked_items(TrackedChs, undefined), diff --git a/deps/rabbit/src/rabbit_log_channel.erl b/deps/rabbit/src/rabbit_log_channel.erl deleted file mode 100644 index e9ffa9c46ade..000000000000 --- a/deps/rabbit/src/rabbit_log_channel.erl +++ /dev/null @@ -1,121 +0,0 @@ -%% This Source Code Form is subject to the terms of the Mozilla Public -%% License, v. 2.0. If a copy of the MPL was not distributed with this -%% file, You can obtain one at https://mozilla.org/MPL/2.0/. -%% -%% Copyright (c) 2007-2025 Broadcom. All Rights Reserved. The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. All rights reserved. -%% - -%% @doc Compatibility module for the old Lager-based logging API. --module(rabbit_log_channel). - --export([debug/1, debug/2, debug/3, - info/1, info/2, info/3, - notice/1, notice/2, notice/3, - warning/1, warning/2, warning/3, - error/1, error/2, error/3, - critical/1, critical/2, critical/3, - alert/1, alert/2, alert/3, - emergency/1, emergency/2, emergency/3, - none/1, none/2, none/3]). - --include_lib("rabbit_common/include/logging.hrl"). --include_lib("kernel/include/logger.hrl"). - --compile({no_auto_import, [error/2, error/3]}). - --spec debug(string()) -> 'ok'. -debug(Format) -> debug(Format, []). - --spec debug(string(), [any()]) -> 'ok'. -debug(Format, Args) -> debug(self(), Format, Args). - --spec debug(pid() | [tuple()], string(), [any()]) -> 'ok'. -debug(Pid, Format, Args) -> - ?LOG_DEBUG(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_CHAN}). - --spec info(string()) -> 'ok'. -info(Format) -> info(Format, []). - --spec info(string(), [any()]) -> 'ok'. -info(Format, Args) -> info(self(), Format, Args). - --spec info(pid() | [tuple()], string(), [any()]) -> 'ok'. -info(Pid, Format, Args) -> - ?LOG_INFO(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_CHAN}). - --spec notice(string()) -> 'ok'. -notice(Format) -> notice(Format, []). - --spec notice(string(), [any()]) -> 'ok'. -notice(Format, Args) -> notice(self(), Format, Args). - --spec notice(pid() | [tuple()], string(), [any()]) -> 'ok'. -notice(Pid, Format, Args) -> - ?LOG_NOTICE(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_CHAN}). - --spec warning(string()) -> 'ok'. -warning(Format) -> warning(Format, []). - --spec warning(string(), [any()]) -> 'ok'. -warning(Format, Args) -> warning(self(), Format, Args). - --spec warning(pid() | [tuple()], string(), [any()]) -> 'ok'. -warning(Pid, Format, Args) -> - ?LOG_WARNING(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_CHAN}). - --spec error(string()) -> 'ok'. -error(Format) -> error(Format, []). - --spec error(string(), [any()]) -> 'ok'. -error(Format, Args) -> error(self(), Format, Args). - --spec error(pid() | [tuple()], string(), [any()]) -> 'ok'. -error(Pid, Format, Args) -> - ?LOG_ERROR(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_CHAN}). - --spec critical(string()) -> 'ok'. -critical(Format) -> critical(Format, []). - --spec critical(string(), [any()]) -> 'ok'. -critical(Format, Args) -> critical(self(), Format, Args). - --spec critical(pid() | [tuple()], string(), [any()]) -> 'ok'. -critical(Pid, Format, Args) -> - ?LOG_CRITICAL(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_CHAN}). - --spec alert(string()) -> 'ok'. -alert(Format) -> alert(Format, []). - --spec alert(string(), [any()]) -> 'ok'. -alert(Format, Args) -> alert(self(), Format, Args). - --spec alert(pid() | [tuple()], string(), [any()]) -> 'ok'. -alert(Pid, Format, Args) -> - ?LOG_ALERT(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_CHAN}). - --spec emergency(string()) -> 'ok'. -emergency(Format) -> emergency(Format, []). - --spec emergency(string(), [any()]) -> 'ok'. -emergency(Format, Args) -> emergency(self(), Format, Args). - --spec emergency(pid() | [tuple()], string(), [any()]) -> 'ok'. -emergency(Pid, Format, Args) -> - ?LOG_EMERGENCY(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_CHAN}). - --spec none(string()) -> 'ok'. -none(_Format) -> ok. - --spec none(string(), [any()]) -> 'ok'. -none(_Format, _Args) -> ok. - --spec none(pid() | [tuple()], string(), [any()]) -> 'ok'. -none(_Pid, _Format, _Args) -> ok. From b7b30ce4d144e5541cdae911479e72bcd04f23a1 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Fri, 11 Jul 2025 13:36:04 +0200 Subject: [PATCH 05/31] [skip ci] Remove rabbit_log_mirroring --- deps/rabbit/src/rabbit_log_mirroring.erl | 123 ----------------------- 1 file changed, 123 deletions(-) delete mode 100644 deps/rabbit/src/rabbit_log_mirroring.erl diff --git a/deps/rabbit/src/rabbit_log_mirroring.erl b/deps/rabbit/src/rabbit_log_mirroring.erl deleted file mode 100644 index fc4c0aef5841..000000000000 --- a/deps/rabbit/src/rabbit_log_mirroring.erl +++ /dev/null @@ -1,123 +0,0 @@ -%% This Source Code Form is subject to the terms of the Mozilla Public -%% License, v. 2.0. If a copy of the MPL was not distributed with this -%% file, You can obtain one at https://mozilla.org/MPL/2.0/. -%% -%% Copyright (c) 2007-2025 Broadcom. All Rights Reserved. The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. All rights reserved. -%% - -%% @doc Compatibility module for the old Lager-based logging API. --module(rabbit_log_mirroring). - --export([debug/1, debug/2, debug/3, - info/1, info/2, info/3, - notice/1, notice/2, notice/3, - warning/1, warning/2, warning/3, - error/1, error/2, error/3, - critical/1, critical/2, critical/3, - alert/1, alert/2, alert/3, - emergency/1, emergency/2, emergency/3, - none/1, none/2, none/3]). - --include_lib("rabbit_common/include/logging.hrl"). --include_lib("kernel/include/logger.hrl"). - --compile({no_auto_import, [error/2, error/3]}). - -%%---------------------------------------------------------------------------- - --spec debug(string()) -> 'ok'. -debug(Format) -> debug(Format, []). - --spec debug(string(), [any()]) -> 'ok'. -debug(Format, Args) -> debug(self(), Format, Args). - --spec debug(pid() | [tuple()], string(), [any()]) -> 'ok'. -debug(Pid, Format, Args) -> - ?LOG_DEBUG(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_MIRRORING}). - --spec info(string()) -> 'ok'. -info(Format) -> info(Format, []). - --spec info(string(), [any()]) -> 'ok'. -info(Format, Args) -> info(self(), Format, Args). - --spec info(pid() | [tuple()], string(), [any()]) -> 'ok'. -info(Pid, Format, Args) -> - ?LOG_INFO(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_MIRRORING}). - --spec notice(string()) -> 'ok'. -notice(Format) -> notice(Format, []). - --spec notice(string(), [any()]) -> 'ok'. -notice(Format, Args) -> notice(self(), Format, Args). - --spec notice(pid() | [tuple()], string(), [any()]) -> 'ok'. -notice(Pid, Format, Args) -> - ?LOG_NOTICE(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_MIRRORING}). - --spec warning(string()) -> 'ok'. -warning(Format) -> warning(Format, []). - --spec warning(string(), [any()]) -> 'ok'. -warning(Format, Args) -> warning(self(), Format, Args). - --spec warning(pid() | [tuple()], string(), [any()]) -> 'ok'. -warning(Pid, Format, Args) -> - ?LOG_WARNING(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_MIRRORING}). - --spec error(string()) -> 'ok'. -error(Format) -> error(Format, []). - --spec error(string(), [any()]) -> 'ok'. -error(Format, Args) -> error(self(), Format, Args). - --spec error(pid() | [tuple()], string(), [any()]) -> 'ok'. -error(Pid, Format, Args) -> - ?LOG_ERROR(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_MIRRORING}). - --spec critical(string()) -> 'ok'. -critical(Format) -> critical(Format, []). - --spec critical(string(), [any()]) -> 'ok'. -critical(Format, Args) -> critical(self(), Format, Args). - --spec critical(pid() | [tuple()], string(), [any()]) -> 'ok'. -critical(Pid, Format, Args) -> - ?LOG_CRITICAL(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_MIRRORING}). - --spec alert(string()) -> 'ok'. -alert(Format) -> alert(Format, []). - --spec alert(string(), [any()]) -> 'ok'. -alert(Format, Args) -> alert(self(), Format, Args). - --spec alert(pid() | [tuple()], string(), [any()]) -> 'ok'. -alert(Pid, Format, Args) -> - ?LOG_ALERT(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_MIRRORING}). - --spec emergency(string()) -> 'ok'. -emergency(Format) -> emergency(Format, []). - --spec emergency(string(), [any()]) -> 'ok'. -emergency(Format, Args) -> emergency(self(), Format, Args). - --spec emergency(pid() | [tuple()], string(), [any()]) -> 'ok'. -emergency(Pid, Format, Args) -> - ?LOG_EMERGENCY(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_MIRRORING}). - --spec none(string()) -> 'ok'. -none(_Format) -> ok. - --spec none(string(), [any()]) -> 'ok'. -none(_Format, _Args) -> ok. - --spec none(pid() | [tuple()], string(), [any()]) -> 'ok'. -none(_Pid, _Format, _Args) -> ok. From 5600138ce9e0832ef943eba1ad1d21c6dcb1f224 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Fri, 11 Jul 2025 13:36:29 +0200 Subject: [PATCH 06/31] [skip ci] Remove rabbit_log_prelaunch --- deps/rabbit/src/rabbit_log_prelaunch.erl | 121 ----------------------- 1 file changed, 121 deletions(-) delete mode 100644 deps/rabbit/src/rabbit_log_prelaunch.erl diff --git a/deps/rabbit/src/rabbit_log_prelaunch.erl b/deps/rabbit/src/rabbit_log_prelaunch.erl deleted file mode 100644 index 0532dfbb97f7..000000000000 --- a/deps/rabbit/src/rabbit_log_prelaunch.erl +++ /dev/null @@ -1,121 +0,0 @@ -%% This Source Code Form is subject to the terms of the Mozilla Public -%% License, v. 2.0. If a copy of the MPL was not distributed with this -%% file, You can obtain one at https://mozilla.org/MPL/2.0/. -%% -%% Copyright (c) 2007-2025 Broadcom. All Rights Reserved. The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. All rights reserved. -%% - -%% @doc Compatibility module for the old Lager-based logging API. --module(rabbit_log_prelaunch). - --export([debug/1, debug/2, debug/3, - info/1, info/2, info/3, - notice/1, notice/2, notice/3, - warning/1, warning/2, warning/3, - error/1, error/2, error/3, - critical/1, critical/2, critical/3, - alert/1, alert/2, alert/3, - emergency/1, emergency/2, emergency/3, - none/1, none/2, none/3]). - --include_lib("rabbit_common/include/logging.hrl"). --include_lib("kernel/include/logger.hrl"). - --compile({no_auto_import, [error/2, error/3]}). - --spec debug(string()) -> 'ok'. -debug(Format) -> debug(Format, []). - --spec debug(string(), [any()]) -> 'ok'. -debug(Format, Args) -> debug(self(), Format, Args). - --spec debug(pid() | [tuple()], string(), [any()]) -> 'ok'. -debug(Pid, Format, Args) -> - ?LOG_DEBUG(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_PRELAUNCH}). - --spec info(string()) -> 'ok'. -info(Format) -> info(Format, []). - --spec info(string(), [any()]) -> 'ok'. -info(Format, Args) -> info(self(), Format, Args). - --spec info(pid() | [tuple()], string(), [any()]) -> 'ok'. -info(Pid, Format, Args) -> - ?LOG_INFO(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_PRELAUNCH}). - --spec notice(string()) -> 'ok'. -notice(Format) -> notice(Format, []). - --spec notice(string(), [any()]) -> 'ok'. -notice(Format, Args) -> notice(self(), Format, Args). - --spec notice(pid() | [tuple()], string(), [any()]) -> 'ok'. -notice(Pid, Format, Args) -> - ?LOG_NOTICE(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_PRELAUNCH}). - --spec warning(string()) -> 'ok'. -warning(Format) -> warning(Format, []). - --spec warning(string(), [any()]) -> 'ok'. -warning(Format, Args) -> warning(self(), Format, Args). - --spec warning(pid() | [tuple()], string(), [any()]) -> 'ok'. -warning(Pid, Format, Args) -> - ?LOG_WARNING(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_PRELAUNCH}). - --spec error(string()) -> 'ok'. -error(Format) -> error(Format, []). - --spec error(string(), [any()]) -> 'ok'. -error(Format, Args) -> error(self(), Format, Args). - --spec error(pid() | [tuple()], string(), [any()]) -> 'ok'. -error(Pid, Format, Args) -> - ?LOG_ERROR(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_PRELAUNCH}). - --spec critical(string()) -> 'ok'. -critical(Format) -> critical(Format, []). - --spec critical(string(), [any()]) -> 'ok'. -critical(Format, Args) -> critical(self(), Format, Args). - --spec critical(pid() | [tuple()], string(), [any()]) -> 'ok'. -critical(Pid, Format, Args) -> - ?LOG_CRITICAL(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_PRELAUNCH}). - --spec alert(string()) -> 'ok'. -alert(Format) -> alert(Format, []). - --spec alert(string(), [any()]) -> 'ok'. -alert(Format, Args) -> alert(self(), Format, Args). - --spec alert(pid() | [tuple()], string(), [any()]) -> 'ok'. -alert(Pid, Format, Args) -> - ?LOG_ALERT(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_PRELAUNCH}). - --spec emergency(string()) -> 'ok'. -emergency(Format) -> emergency(Format, []). - --spec emergency(string(), [any()]) -> 'ok'. -emergency(Format, Args) -> emergency(self(), Format, Args). - --spec emergency(pid() | [tuple()], string(), [any()]) -> 'ok'. -emergency(Pid, Format, Args) -> - ?LOG_EMERGENCY(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_PRELAUNCH}). - --spec none(string()) -> 'ok'. -none(_Format) -> ok. - --spec none(string(), [any()]) -> 'ok'. -none(_Format, _Args) -> ok. - --spec none(pid() | [tuple()], string(), [any()]) -> 'ok'. -none(_Pid, _Format, _Args) -> ok. From 3ee8df9310353bc764fecb900d85ce36c97a5653 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Fri, 11 Jul 2025 15:51:58 +0200 Subject: [PATCH 07/31] [skip ci] Remove `pid` from logger process metadata It's added automatically by logger --- deps/rabbit/src/rabbit_amqqueue_process.erl | 3 +-- deps/rabbit/src/rabbit_channel.erl | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/deps/rabbit/src/rabbit_amqqueue_process.erl b/deps/rabbit/src/rabbit_amqqueue_process.erl index aca2d9b6cbe8..3f01ce932389 100644 --- a/deps/rabbit/src/rabbit_amqqueue_process.erl +++ b/deps/rabbit/src/rabbit_amqqueue_process.erl @@ -144,8 +144,7 @@ start_link(Q, Marker) -> gen_server2:start_link(?MODULE, {Q, Marker}, []). init({Q, Marker}) -> - logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_QUEUE, - pid => self()}), + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_QUEUE}), case is_process_alive(Marker) of true -> %% start diff --git a/deps/rabbit/src/rabbit_channel.erl b/deps/rabbit/src/rabbit_channel.erl index 7248bf906f34..649270bc7d1e 100644 --- a/deps/rabbit/src/rabbit_channel.erl +++ b/deps/rabbit/src/rabbit_channel.erl @@ -467,8 +467,7 @@ init([Channel, ReaderPid, WriterPid, ConnPid, ConnName, Protocol, User, VHost, Capabilities, CollectorPid, LimiterPid, AmqpParams]) -> process_flag(trap_exit, true), rabbit_process_flag:adjust_for_message_handling_proc(), - logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_CHAN, - pid => self()}), + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_CHAN}), ?LG_PROCESS_TYPE(channel), ?store_proc_name({ConnName, Channel}), From ebe3f61ef0db2e1090644e8db25b5f3311f40b30 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Fri, 11 Jul 2025 15:49:34 +0200 Subject: [PATCH 08/31] [skip ci] Remove rabbit_log_federation and use LOG_ macros --- .../src/rabbit_exchange_federation_app.erl | 2 + .../src/rabbit_federation_exchange_link.erl | 36 +++--- ...abbit_federation_exchange_link_sup_sup.erl | 12 +- .../src/rabbit_federation_link_util.erl | 66 ++++------- .../src/rabbit_federation_pg.erl | 4 +- .../src/rabbit_log_federation.erl | 108 ------------------ .../src/rabbit_federation_queue_link.erl | 6 +- .../rabbit_federation_queue_link_sup_sup.erl | 11 +- .../src/rabbit_queue_federation_app.erl | 1 + 9 files changed, 65 insertions(+), 181 deletions(-) delete mode 100644 deps/rabbitmq_federation_common/src/rabbit_log_federation.erl diff --git a/deps/rabbitmq_exchange_federation/src/rabbit_exchange_federation_app.erl b/deps/rabbitmq_exchange_federation/src/rabbit_exchange_federation_app.erl index dfdc0677d10b..28b79a27a2e3 100644 --- a/deps/rabbitmq_exchange_federation/src/rabbit_exchange_federation_app.erl +++ b/deps/rabbitmq_exchange_federation/src/rabbit_exchange_federation_app.erl @@ -9,6 +9,7 @@ -include_lib("rabbitmq_federation_common/include/rabbit_federation.hrl"). -include("rabbit_exchange_federation.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(application). -export([start/2, stop/1]). @@ -43,6 +44,7 @@ stop(_State) -> %%---------------------------------------------------------------------------- init([]) -> + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_FEDERATION}), Flags = #{ strategy => one_for_one, intensity => 3, diff --git a/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link.erl b/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link.erl index fbdcd396681c..997e9e21e3a4 100644 --- a/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link.erl +++ b/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link.erl @@ -65,6 +65,8 @@ start_link(Args) -> gen_server2:start_link(?MODULE, Args, [{timeout, infinity}]). init({Upstream, XName}) -> + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_FEDERATION, + exchange => XName}), %% If we are starting up due to a policy change then it's possible %% for the exchange to have been deleted before we got here, in which %% case it's possible that delete callback would also have been called @@ -80,7 +82,7 @@ init({Upstream, XName}) -> gen_server2:cast(self(), maybe_go), {ok, {not_started, {Upstream, UParams, XName}}}; {error, not_found} -> - rabbit_federation_link_util:log_warning(XName, "not found, stopping link", []), + ?LOG_WARNING("not found, stopping link", []), {stop, gone} end. @@ -105,14 +107,12 @@ handle_cast({enqueue, _, _}, State = {not_started, _}) -> {noreply, State}; handle_cast({enqueue, Serial, Cmd}, - State = #state{waiting_cmds = Waiting, - downstream_exchange = XName}) -> + State = #state{waiting_cmds = Waiting}) -> Waiting1 = gb_trees:insert(Serial, Cmd, Waiting), try {noreply, play_back_commands(State#state{waiting_cmds = Waiting1})} catch exit:{{shutdown, {server_initiated_close, 404, Text}}, _} -> - rabbit_federation_link_util:log_warning( - XName, "detected upstream changes, restarting link: ~tp", [Text]), + ?LOG_WARNING("detected upstream changes, restarting link: ~tp", [Text]), {stop, {shutdown, restart}, State} end; @@ -177,7 +177,7 @@ handle_info(check_internal_exchange, State = #state{internal_exchange = IntXName internal_exchange_interval = Interval}) -> case check_internal_exchange(IntXNameBin, State) of upstream_not_found -> - rabbit_log_federation:warning("Federation link could not find upstream exchange '~ts' and will restart", + ?LOG_WARNING("Federation link could not find upstream exchange '~ts' and will restart", [IntXNameBin]), {stop, {shutdown, restart}, State}; _ -> @@ -470,25 +470,25 @@ go(S0 = {not_started, {Upstream, UParams, DownXName}}) -> unacked = Unacked, internal_exchange_interval = Interval}), Bindings), - rabbit_log_federation:info("Federation link for ~ts (upstream: ~ts) will perform internal exchange checks " + ?LOG_INFO("Federation link for ~ts (upstream: ~ts) will perform internal exchange checks " "every ~b seconds", [rabbit_misc:rs(DownXName), UName, round(Interval / 1000)]), TRef = erlang:send_after(Interval, self(), check_internal_exchange), {noreply, State#state{internal_exchange_timer = TRef}} end, Upstream, UParams, DownXName, S0). log_link_startup_attempt(#upstream{name = Name, channel_use_mode = ChMode}, DownXName) -> - rabbit_log_federation:debug("Will try to start a federation link for ~ts, upstream: '~ts', channel use mode: ~ts", + ?LOG_DEBUG("Will try to start a federation link for ~ts, upstream: '~ts', channel use mode: ~ts", [rabbit_misc:rs(DownXName), Name, ChMode]). %% If channel use mode is 'single', reuse the message transfer channel. %% Otherwise open a separate one. reuse_command_channel(MainCh, #upstream{name = UName}, DownXName) -> - rabbit_log_federation:debug("Will use a single channel for both schema operations and message transfer on links to upstream '~ts' for downstream federated ~ts", + ?LOG_DEBUG("Will use a single channel for both schema operations and message transfer on links to upstream '~ts' for downstream federated ~ts", [UName, rabbit_misc:rs(DownXName)]), {ok, MainCh}. open_command_channel(Conn, Upstream = #upstream{name = UName}, UParams, DownXName, S0) -> - rabbit_log_federation:debug("Will open a command channel to upstream '~ts' for downstream federated ~ts", + ?LOG_DEBUG("Will open a command channel to upstream '~ts' for downstream federated ~ts", [UName, rabbit_misc:rs(DownXName)]), case amqp_connection:open_channel(Conn) of {ok, CCh} -> @@ -583,12 +583,12 @@ ensure_internal_exchange(IntXNameBin, connection = Conn, channel = Ch, downstream_exchange = #resource{virtual_host = DVhost}}) -> - rabbit_log_federation:debug("Exchange federation will set up exchange '~ts' in upstream '~ts'", + ?LOG_DEBUG("Exchange federation will set up exchange '~ts' in upstream '~ts'", [IntXNameBin, UName]), #upstream_params{params = Params} = rabbit_federation_util:deobfuscate_upstream_params(UParams), - rabbit_log_federation:debug("Will delete upstream exchange '~ts'", [IntXNameBin]), + ?LOG_DEBUG("Will delete upstream exchange '~ts'", [IntXNameBin]), delete_upstream_exchange(Conn, IntXNameBin), - rabbit_log_federation:debug("Will declare an internal upstream exchange '~ts'", [IntXNameBin]), + ?LOG_DEBUG("Will declare an internal upstream exchange '~ts'", [IntXNameBin]), Base = #'exchange.declare'{exchange = IntXNameBin, durable = true, internal = true, @@ -613,7 +613,7 @@ check_internal_exchange(IntXNameBin, downstream_exchange = XName = #resource{virtual_host = DVhost}}) -> #upstream_params{params = Params} = rabbit_federation_util:deobfuscate_upstream_params(UParams), - rabbit_log_federation:debug("Exchange federation will check on exchange '~ts' in upstream '~ts'", + ?LOG_DEBUG("Exchange federation will check on exchange '~ts' in upstream '~ts'", [IntXNameBin, UName]), Base = #'exchange.declare'{exchange = IntXNameBin, passive = true, @@ -629,13 +629,11 @@ check_internal_exchange(IntXNameBin, arguments = XFUArgs}, rabbit_federation_link_util:disposable_connection_call( Params, XFU, fun(404, Text) -> - rabbit_federation_link_util:log_warning( - XName, "detected internal upstream exchange changes," - " restarting link: ~tp", [Text]), + ?LOG_WARNING("detected internal upstream exchange changes," + " restarting link: ~tp", [Text]), upstream_not_found; (Code, Text) -> - rabbit_federation_link_util:log_warning( - XName, "internal upstream exchange check failed: ~tp ~tp", + ?LOG_WARNING("internal upstream exchange check failed: ~tp ~tp", [Code, Text]), error end). diff --git a/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link_sup_sup.erl b/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link_sup_sup.erl index 4371fb0f0b7c..8b36e4b6d916 100644 --- a/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link_sup_sup.erl +++ b/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link_sup_sup.erl @@ -11,6 +11,8 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include("rabbit_exchange_federation.hrl"). +-include_lib("kernel/include/logger.hrl"). +-include_lib("rabbit_federation.hrl"). -define(SUPERVISOR, ?MODULE). %% Supervises the upstream links for all exchanges (but not queues). We need @@ -43,8 +45,8 @@ start_child(X) -> {ok, _Pid} -> ok; {error, {already_started, _Pid}} -> #exchange{name = ExchangeName} = X, - rabbit_log_federation:debug("Federation link for exchange ~tp was already started", - [rabbit_misc:rs(ExchangeName)]), + ?LOG_DEBUG("Federation link for exchange ~tp was already started", + [rabbit_misc:rs(ExchangeName)]), ok; %% A link returned {stop, gone}, the link_sup shut down, that's OK. {error, {shutdown, _}} -> ok @@ -67,9 +69,8 @@ stop_child(X) -> ok -> ok; {error, Err} -> #exchange{name = ExchangeName} = X, - rabbit_log_federation:warning( - "Attempt to stop a federation link for exchange ~tp failed: ~tp", - [rabbit_misc:rs(ExchangeName), Err]), + ?LOG_WARNING("Attempt to stop a federation link for exchange ~tp failed: ~tp", + [rabbit_misc:rs(ExchangeName), Err]), ok end, ok = mirrored_supervisor:delete_child(?SUPERVISOR, id(X)). @@ -77,6 +78,7 @@ stop_child(X) -> %%---------------------------------------------------------------------------- init([]) -> + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_FEDERATION}), {ok, {{one_for_one, 1200, 60}, []}}. %% See comment in rabbit_federation_queue_link_sup_sup:id/1 diff --git a/deps/rabbitmq_federation_common/src/rabbit_federation_link_util.erl b/deps/rabbitmq_federation_common/src/rabbit_federation_link_util.erl index 16c87d2cc9c7..e2d72d38a6c7 100644 --- a/deps/rabbitmq_federation_common/src/rabbit_federation_link_util.erl +++ b/deps/rabbitmq_federation_common/src/rabbit_federation_link_util.erl @@ -10,14 +10,14 @@ -include_lib("rabbit/include/amqqueue.hrl"). -include_lib("amqp_client/include/amqp_client.hrl"). -include("rabbit_federation.hrl"). +-include_lib("kernel/include/logger.hrl"). %% real -export([start_conn_ch/5, disposable_channel_call/2, disposable_channel_call/3, disposable_connection_call/3, ensure_connection_closed/1, log_terminate/4, unacked_new/0, ack/3, nack/3, forward/9, handle_downstream_down/3, handle_upstream_down/3, - get_connection_name/2, log_debug/3, log_info/3, log_warning/3, - log_error/3]). + get_connection_name/2]). %% temp -export([connection_error/6]). @@ -55,10 +55,9 @@ start_conn_ch(Fun, OUpstream, OUParams, process_flag(trap_exit, true), try R = Fun(Conn, Ch, DConn, DCh), - log_info( - XorQName, "connected to ~ts", - [rabbit_federation_upstream:params_to_string( - UParams)]), + ?LOG_INFO("Federation ~ts connected to ~ts", + [rabbit_misc:rs(XorQName), + rabbit_federation_upstream:params_to_string(UParams)]), Name = pget(name, amqp_connection:info(DConn, [name])), rabbit_federation_status:report( OUpstream, OUParams, XorQName, {running, Name}), @@ -130,45 +129,44 @@ connection_error(remote_start, {{shutdown, {server_initiated_close, Code, Messag Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(E)), - log_warning(XorQName, - "did not connect to ~ts. Server has closed the connection due to an error, code: ~tp, " + ?LOG_WARNING("Federation ~ts did not connect to ~ts. Server has closed the connection due to an error, code: ~tp, " "message: ~ts", - [rabbit_federation_upstream:params_to_string(UParams), + [rabbit_misc:rs(XorQName), rabbit_federation_upstream:params_to_string(UParams), Code, Message]), {stop, {shutdown, restart}, State}; connection_error(remote_start, E, Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(E)), - log_warning(XorQName, "did not connect to ~ts. Reason: ~tp", - [rabbit_federation_upstream:params_to_string(UParams), + ?LOG_WARNING("Federation ~ts did not connect to ~ts. Reason: ~tp", + [rabbit_misc:rs(XorQName), rabbit_federation_upstream:params_to_string(UParams), E]), {stop, {shutdown, restart}, State}; connection_error(remote, E, Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(E)), - log_info(XorQName, "disconnected from ~ts~n~tp", - [rabbit_federation_upstream:params_to_string(UParams), E]), + ?LOG_INFO("Federation ~ts disconnected from ~ts~n~tp", + [rabbit_misc:rs(XorQName), rabbit_federation_upstream:params_to_string(UParams), E]), {stop, {shutdown, restart}, State}; connection_error(command_channel, E, Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(E)), - log_info(XorQName, "failed to open a command channel for upstream ~ts~n~tp", - [rabbit_federation_upstream:params_to_string(UParams), E]), + ?LOG_INFO("Federation ~ts failed to open a command channel for upstream ~ts~n~tp", + [rabbit_misc:rs(XorQName), rabbit_federation_upstream:params_to_string(UParams), E]), {stop, {shutdown, restart}, State}; connection_error(local, basic_cancel, Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, {error, basic_cancel}), - log_info(XorQName, "received a 'basic.cancel'", []), + ?LOG_INFO("Federation ~ts received a 'basic.cancel'", [rabbit_misc:rs(XorQName)]), {stop, {shutdown, restart}, State}; connection_error(local_start, E, Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(E)), - log_warning(XorQName, "did not connect locally~n~tp", [E]), + ?LOG_WARNING("Federation ~ts did not connect locally~n~tp", [rabbit_misc:rs(XorQName), E]), {stop, {shutdown, restart}, State}. %% If we terminate due to a gen_server call exploding (almost @@ -285,7 +283,7 @@ log_terminate(shutdown, Upstream, UParams, XorQName) -> %% the link because configuration has changed. So try to shut down %% nicely so that we do not cause unacked messages to be %% redelivered. - log_info(XorQName, "disconnecting from ~ts", + ?LOG_INFO("disconnecting from ~ts", [rabbit_federation_upstream:params_to_string(UParams)]), rabbit_federation_status:remove(Upstream, XorQName); @@ -295,21 +293,6 @@ log_terminate(Reason, Upstream, UParams, XorQName) -> rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(Reason)). -log_debug(XorQName, Fmt, Args) -> log(debug, XorQName, Fmt, Args). -log_info(XorQName, Fmt, Args) -> log(info, XorQName, Fmt, Args). -log_warning(XorQName, Fmt, Args) -> log(warning, XorQName, Fmt, Args). -log_error(XorQName, Fmt, Args) -> log(error, XorQName, Fmt, Args). - -log(Level, XorQName, Fmt0, Args0) -> - Fmt = "Federation ~ts " ++ Fmt0, - Args = [rabbit_misc:rs(XorQName) | Args0], - case Level of - debug -> rabbit_log_federation:debug(Fmt, Args); - info -> rabbit_log_federation:info(Fmt, Args); - warning -> rabbit_log_federation:warning(Fmt, Args); - error -> rabbit_log_federation:error(Fmt, Args) - end. - %%---------------------------------------------------------------------------- disposable_channel_call(Conn, Method) -> @@ -327,12 +310,13 @@ disposable_channel_call(Conn, Method, ErrFun) -> end catch Exception:Reason -> - rabbit_log_federation:error("Federation link could not create a disposable (one-off) channel due to an error ~tp: ~tp", [Exception, Reason]) + ?LOG_ERROR("Federation link could not create a disposable (one-off) channel due to an error ~tp: ~tp", + [Exception, Reason]) end. disposable_connection_call(Params, Method, ErrFun) -> try - rabbit_log_federation:debug("Disposable connection parameters: ~tp", [Params]), + ?LOG_DEBUG("Disposable connection parameters: ~tp", [Params]), case open(Params, <<"Disposable exchange federation link connection">>) of {ok, Conn, Ch} -> try @@ -345,15 +329,15 @@ disposable_connection_call(Params, Method, ErrFun) -> ensure_connection_closed(Conn) end; {error, {auth_failure, Message}} -> - rabbit_log_federation:error("Federation link could not open a disposable (one-off) connection " - "due to an authentication failure: ~ts", [Message]); + ?LOG_ERROR("Federation link could not open a disposable (one-off) connection " + "due to an authentication failure: ~ts", [Message]); Error -> - rabbit_log_federation:error("Federation link could not open a disposable (one-off) connection, " - "reason: ~tp", [Error]), + ?LOG_ERROR("Federation link could not open a disposable (one-off) connection, " + "reason: ~tp", [Error]), Error end catch Exception:Reason -> - rabbit_log_federation:error("Federation link could not create a disposable (one-off) connection " - "due to an error ~tp: ~tp", [Exception, Reason]) + ?LOG_ERROR("Federation link could not create a disposable (one-off) connection " + "due to an error ~tp: ~tp", [Exception, Reason]) end. diff --git a/deps/rabbitmq_federation_common/src/rabbit_federation_pg.erl b/deps/rabbitmq_federation_common/src/rabbit_federation_pg.erl index 7fe1eb612b23..b23311690198 100644 --- a/deps/rabbitmq_federation_common/src/rabbit_federation_pg.erl +++ b/deps/rabbitmq_federation_common/src/rabbit_federation_pg.erl @@ -13,13 +13,13 @@ -export([start_scope/1, stop_scope/1]). start_scope(Scope) -> - rabbit_log_federation:debug("Starting pg scope ~ts", [Scope]), + ?LOG_DEBUG("Starting pg scope ~ts", [Scope]), _ = pg:start_link(Scope). stop_scope(Scope) -> case whereis(Scope) of Pid when is_pid(Pid) -> - rabbit_log_federation:debug("Stopping pg scope ~ts", [Scope]), + ?LOG_DEBUG("Stopping pg scope ~ts", [Scope]), Groups = pg:which_groups(Scope), lists:foreach( fun(Group) -> diff --git a/deps/rabbitmq_federation_common/src/rabbit_log_federation.erl b/deps/rabbitmq_federation_common/src/rabbit_log_federation.erl deleted file mode 100644 index 1704935ee273..000000000000 --- a/deps/rabbitmq_federation_common/src/rabbit_log_federation.erl +++ /dev/null @@ -1,108 +0,0 @@ -%% This Source Code Form is subject to the terms of the Mozilla Public -%% License, v. 2.0. If a copy of the MPL was not distributed with this -%% file, You can obtain one at https://mozilla.org/MPL/2.0/. -%% -%% Copyright (c) 2007-2025 Broadcom. All Rights Reserved. The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. All rights reserved. -%% - -%% @doc Compatibility module for the old Lager-based logging API. --module(rabbit_log_federation). - --export([debug/1, debug/2, debug/3, - info/1, info/2, info/3, - notice/1, notice/2, notice/3, - warning/1, warning/2, warning/3, - error/1, error/2, error/3, - critical/1, critical/2, critical/3, - alert/1, alert/2, alert/3, - emergency/1, emergency/2, emergency/3, - none/1, none/2, none/3]). - --include("logging.hrl"). --include_lib("kernel/include/logger.hrl"). - --compile({no_auto_import, [error/2, error/3]}). - -%%---------------------------------------------------------------------------- - --spec debug(string()) -> 'ok'. --spec debug(string(), [any()]) -> 'ok'. --spec debug(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec info(string()) -> 'ok'. --spec info(string(), [any()]) -> 'ok'. --spec info(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec notice(string()) -> 'ok'. --spec notice(string(), [any()]) -> 'ok'. --spec notice(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec warning(string()) -> 'ok'. --spec warning(string(), [any()]) -> 'ok'. --spec warning(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec error(string()) -> 'ok'. --spec error(string(), [any()]) -> 'ok'. --spec error(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec critical(string()) -> 'ok'. --spec critical(string(), [any()]) -> 'ok'. --spec critical(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec alert(string()) -> 'ok'. --spec alert(string(), [any()]) -> 'ok'. --spec alert(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec emergency(string()) -> 'ok'. --spec emergency(string(), [any()]) -> 'ok'. --spec emergency(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec none(string()) -> 'ok'. --spec none(string(), [any()]) -> 'ok'. --spec none(pid() | [tuple()], string(), [any()]) -> 'ok'. - -%%---------------------------------------------------------------------------- - -debug(Format) -> debug(Format, []). -debug(Format, Args) -> debug(self(), Format, Args). -debug(Pid, Format, Args) -> - ?LOG_DEBUG(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_FEDERATION}). - -info(Format) -> info(Format, []). -info(Format, Args) -> info(self(), Format, Args). -info(Pid, Format, Args) -> - ?LOG_INFO(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_FEDERATION}). - -notice(Format) -> notice(Format, []). -notice(Format, Args) -> notice(self(), Format, Args). -notice(Pid, Format, Args) -> - ?LOG_NOTICE(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_FEDERATION}). - -warning(Format) -> warning(Format, []). -warning(Format, Args) -> warning(self(), Format, Args). -warning(Pid, Format, Args) -> - ?LOG_WARNING(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_FEDERATION}). - -error(Format) -> error(Format, []). -error(Format, Args) -> error(self(), Format, Args). -error(Pid, Format, Args) -> - ?LOG_ERROR(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_FEDERATION}). - -critical(Format) -> critical(Format, []). -critical(Format, Args) -> critical(self(), Format, Args). -critical(Pid, Format, Args) -> - ?LOG_CRITICAL(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_FEDERATION}). - -alert(Format) -> alert(Format, []). -alert(Format, Args) -> alert(self(), Format, Args). -alert(Pid, Format, Args) -> - ?LOG_ALERT(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_FEDERATION}). - -emergency(Format) -> emergency(Format, []). -emergency(Format, Args) -> emergency(self(), Format, Args). -emergency(Pid, Format, Args) -> - ?LOG_EMERGENCY(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_FEDERATION}). - -none(_Format) -> ok. -none(_Format, _Args) -> ok. -none(_Pid, _Format, _Args) -> ok. diff --git a/deps/rabbitmq_queue_federation/src/rabbit_federation_queue_link.erl b/deps/rabbitmq_queue_federation/src/rabbit_federation_queue_link.erl index 11d0598ba3e6..f91a4013f0dd 100644 --- a/deps/rabbitmq_queue_federation/src/rabbit_federation_queue_link.erl +++ b/deps/rabbitmq_queue_federation/src/rabbit_federation_queue_link.erl @@ -10,7 +10,9 @@ -include_lib("rabbit/include/amqqueue.hrl"). -include_lib("amqp_client/include/amqp_client.hrl"). -include_lib("rabbitmq_federation_common/include/rabbit_federation.hrl"). +-include_lib("rabbitmq_federation_common/include/logging.hrl"). -include("rabbit_queue_federation.hrl"). +-include_lib("kernel/include/logger.hrl"). -behaviour(gen_server2). @@ -53,6 +55,8 @@ q(QName) -> init({Upstream, Queue}) when ?is_amqqueue(Queue) -> QName = amqqueue:get_name(Queue), + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_FEDERATION, + queue => QName}), case rabbit_amqqueue:lookup(QName) of {ok, Q} -> DeobfuscatedUpstream = rabbit_federation_util:deobfuscate_upstream(Upstream), @@ -68,7 +72,7 @@ init({Upstream, Queue}) when ?is_amqqueue(Queue) -> upstream = Upstream, upstream_params = UParams}}; {error, not_found} -> - rabbit_federation_link_util:log_warning(QName, "not found, stopping link", []), + ?LOG_WARNING("not found, stopping link", []), {stop, gone} end. diff --git a/deps/rabbitmq_queue_federation/src/rabbit_federation_queue_link_sup_sup.erl b/deps/rabbitmq_queue_federation/src/rabbit_federation_queue_link_sup_sup.erl index 945c5d35cc85..29d2ee88d15b 100644 --- a/deps/rabbitmq_queue_federation/src/rabbit_federation_queue_link_sup_sup.erl +++ b/deps/rabbitmq_queue_federation/src/rabbit_federation_queue_link_sup_sup.erl @@ -12,6 +12,8 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include_lib("rabbit/include/amqqueue.hrl"). -include("rabbit_queue_federation.hrl"). +-include_lib("kernel/include/logger.hrl"). +-include("rabbit_federation.hrl"). -define(SUPERVISOR, ?MODULE). %% Supervises the upstream links for all queues (but not exchanges). We need @@ -43,8 +45,8 @@ start_child(Q) -> {ok, _Pid} -> ok; {error, {already_started, _Pid}} -> QueueName = amqqueue:get_name(Q), - rabbit_log_federation:warning("Federation link for queue ~tp was already started", - [rabbit_misc:rs(QueueName)]), + ?LOG_WARNING("Federation link for queue ~tp was already started", + [rabbit_misc:rs(QueueName)]), ok; %% A link returned {stop, gone}, the link_sup shut down, that's OK. {error, {shutdown, _}} -> ok @@ -66,9 +68,8 @@ stop_child(Q) -> ok -> ok; {error, Err} -> QueueName = amqqueue:get_name(Q), - rabbit_log_federation:warning( - "Attempt to stop a federation link for queue ~tp failed: ~tp", - [rabbit_misc:rs(QueueName), Err]), + ?LOG_WARNING("Attempt to stop a federation link for queue ~tp failed: ~tp", + [rabbit_misc:rs(QueueName), Err]), ok end, _ = mirrored_supervisor:delete_child(?SUPERVISOR, id(Q)). diff --git a/deps/rabbitmq_queue_federation/src/rabbit_queue_federation_app.erl b/deps/rabbitmq_queue_federation/src/rabbit_queue_federation_app.erl index 541a59d4db0d..60c75eae69f3 100644 --- a/deps/rabbitmq_queue_federation/src/rabbit_queue_federation_app.erl +++ b/deps/rabbitmq_queue_federation/src/rabbit_queue_federation_app.erl @@ -43,6 +43,7 @@ stop(_State) -> %%---------------------------------------------------------------------------- init([]) -> + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_FEDERATION}), Flags = #{ strategy => one_for_one, intensity => 3, From 8a054338970fe2038037fc6fa51203209a8ba3ef Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Fri, 11 Jul 2025 16:25:27 +0200 Subject: [PATCH 09/31] [skip ci] Remove rabbit_log_connection and use LOG_ macros --- .../rabbit/src/rabbit_connection_tracking.erl | 10 +- .../rabbit_connection_tracking_handler.erl | 2 + deps/rabbit/src/rabbit_direct.erl | 11 +- deps/rabbit/src/rabbit_log_connection.erl | 121 ------------------ deps/rabbit/src/rabbit_reader.erl | 44 ++++--- .../src/rabbit_stomp_reader.erl | 30 +++-- .../src/rabbit_stream_reader.erl | 90 ++++++------- .../src/rabbit_web_stomp_handler.erl | 8 +- .../src/rabbit_web_stomp_listener.erl | 14 +- 9 files changed, 113 insertions(+), 217 deletions(-) delete mode 100644 deps/rabbit/src/rabbit_log_connection.erl diff --git a/deps/rabbit/src/rabbit_connection_tracking.erl b/deps/rabbit/src/rabbit_connection_tracking.erl index 1716742432eb..f38e982451a6 100644 --- a/deps/rabbit/src/rabbit_connection_tracking.erl +++ b/deps/rabbit/src/rabbit_connection_tracking.erl @@ -78,11 +78,11 @@ handle_cast({connection_created, Details}) -> error:{no_exists, _} -> Msg = "Could not register connection ~tp for tracking, " "its table is not ready yet or the connection terminated prematurely", - rabbit_log_connection:warning(Msg, [ConnId]), + ?LOG_WARNING(Msg, [ConnId]), ok; error:Err -> Msg = "Could not register connection ~tp for tracking: ~tp", - rabbit_log_connection:warning(Msg, [ConnId, Err]), + ?LOG_WARNING(Msg, [ConnId, Err]), ok end; _OtherNode -> @@ -107,7 +107,7 @@ handle_cast({vhost_deleted, Details}) -> %% Schedule vhost entry deletion, allowing time for connections to close _ = timer:apply_after(?TRACKING_EXECUTION_TIMEOUT, ?MODULE, delete_tracked_connection_vhost_entry, [VHost]), - rabbit_log_connection:info("Closing all connections in vhost '~ts' because it's being deleted", [VHost]), + ?LOG_INFO("Closing all connections in vhost '~ts' because it's being deleted", [VHost]), shutdown_tracked_items( list(VHost), rabbit_misc:format("vhost '~ts' is deleted", [VHost])); @@ -117,7 +117,7 @@ handle_cast({vhost_deleted, Details}) -> handle_cast({vhost_down, Details}) -> VHost = pget(name, Details), Node = pget(node, Details), - rabbit_log_connection:info("Closing all connections in vhost '~ts' on node '~ts'" + ?LOG_INFO("Closing all connections in vhost '~ts' on node '~ts'" " because the vhost is stopping", [VHost, Node]), shutdown_tracked_items( @@ -128,7 +128,7 @@ handle_cast({user_deleted, Details}) -> %% Schedule user entry deletion, allowing time for connections to close _ = timer:apply_after(?TRACKING_EXECUTION_TIMEOUT, ?MODULE, delete_tracked_connection_user_entry, [Username]), - rabbit_log_connection:info("Closing all connections for user '~ts' because the user is being deleted", [Username]), + ?LOG_INFO("Closing all connections for user '~ts' because the user is being deleted", [Username]), shutdown_tracked_items( list_of_user(Username), rabbit_misc:format("user '~ts' is deleted", [Username])). diff --git a/deps/rabbit/src/rabbit_connection_tracking_handler.erl b/deps/rabbit/src/rabbit_connection_tracking_handler.erl index d4cb45ab7f34..d8be76efdcd9 100644 --- a/deps/rabbit/src/rabbit_connection_tracking_handler.erl +++ b/deps/rabbit/src/rabbit_connection_tracking_handler.erl @@ -22,6 +22,7 @@ -export([close_connections/3]). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("rabbit_common/include/logging.hrl"). -rabbit_boot_step({?MODULE, [{description, "connection tracking event handler"}, @@ -37,6 +38,7 @@ %% init([]) -> + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_CONN}), {ok, []}. handle_event(#event{type = connection_created, props = Details}, State) -> diff --git a/deps/rabbit/src/rabbit_direct.erl b/deps/rabbit/src/rabbit_direct.erl index 6f70450d085b..9f9a601bb25a 100644 --- a/deps/rabbit/src/rabbit_direct.erl +++ b/deps/rabbit/src/rabbit_direct.erl @@ -20,6 +20,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include_lib("rabbit_common/include/rabbit_misc.hrl"). +-include_lib("kernel/include/logger.hrl"). %%---------------------------------------------------------------------------- @@ -157,7 +158,7 @@ is_vhost_alive(VHost, {Username, _Password}, Pid) -> case rabbit_vhost_sup_sup:is_vhost_alive(VHost) of true -> true; false -> - rabbit_log_connection:error( + ?LOG_ERROR( "Error on direct client connection ~tp~n" "access to vhost '~ts' refused for user '~ts': " "vhost '~ts' is down", @@ -173,7 +174,7 @@ is_over_vhost_connection_limit(VHost, {Username, _Password}, Pid) -> try rabbit_vhost_limit:is_over_connection_limit(VHost) of false -> false; {true, Limit} -> - rabbit_log_connection:error( + ?LOG_ERROR( "Error on direct client connection ~tp~n" "access to vhost '~ts' refused for user '~ts': " "vhost connection limit (~tp) is reached", @@ -181,7 +182,7 @@ is_over_vhost_connection_limit(VHost, {Username, _Password}, Pid) -> true catch throw:{error, {no_such_vhost, VHost}} -> - rabbit_log_connection:error( + ?LOG_ERROR( "Error on direct client connection ~tp~n" "vhost ~ts not found", [Pid, VHost]), true @@ -211,7 +212,7 @@ connect1(User = #user{username = Username}, VHost, Protocol, Pid, Infos) -> {error, Reason} end; {true, Limit} -> - rabbit_log_connection:error( + ?LOG_ERROR( "Error on Direct connection ~tp~n" "access refused for user '~ts': " "user connection limit (~tp) is reached", @@ -237,7 +238,7 @@ start_channel(Number, ClientChannelPid, ConnPid, ConnName, Protocol, User, VHost, Capabilities, Collector, AmqpParams}]), {ok, ChannelPid}; {true, Limit} -> - rabbit_log_connection:error( + ?LOG_ERROR( "Error on direct connection ~tp~n" "number of channels opened for user '~ts' has reached the " "maximum allowed limit of (~w)", diff --git a/deps/rabbit/src/rabbit_log_connection.erl b/deps/rabbit/src/rabbit_log_connection.erl deleted file mode 100644 index cc46aae4bc28..000000000000 --- a/deps/rabbit/src/rabbit_log_connection.erl +++ /dev/null @@ -1,121 +0,0 @@ -%% This Source Code Form is subject to the terms of the Mozilla Public -%% License, v. 2.0. If a copy of the MPL was not distributed with this -%% file, You can obtain one at https://mozilla.org/MPL/2.0/. -%% -%% Copyright (c) 2007-2025 Broadcom. All Rights Reserved. The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. All rights reserved. -%% - -%% @doc Compatibility module for the old Lager-based logging API. --module(rabbit_log_connection). - --export([debug/1, debug/2, debug/3, - info/1, info/2, info/3, - notice/1, notice/2, notice/3, - warning/1, warning/2, warning/3, - error/1, error/2, error/3, - critical/1, critical/2, critical/3, - alert/1, alert/2, alert/3, - emergency/1, emergency/2, emergency/3, - none/1, none/2, none/3]). - --include_lib("rabbit_common/include/logging.hrl"). --include_lib("kernel/include/logger.hrl"). - --compile({no_auto_import, [error/2, error/3]}). - --spec debug(string()) -> 'ok'. -debug(Format) -> debug(Format, []). - --spec debug(string(), [any()]) -> 'ok'. -debug(Format, Args) -> debug(self(), Format, Args). - --spec debug(pid() | [tuple()], string(), [any()]) -> 'ok'. -debug(Pid, Format, Args) -> - ?LOG_DEBUG(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_CONN}). - --spec info(string()) -> 'ok'. -info(Format) -> info(Format, []). - --spec info(string(), [any()]) -> 'ok'. -info(Format, Args) -> info(self(), Format, Args). - --spec info(pid() | [tuple()], string(), [any()]) -> 'ok'. -info(Pid, Format, Args) -> - ?LOG_INFO(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_CONN}). - --spec notice(string()) -> 'ok'. -notice(Format) -> notice(Format, []). - --spec notice(string(), [any()]) -> 'ok'. -notice(Format, Args) -> notice(self(), Format, Args). - --spec notice(pid() | [tuple()], string(), [any()]) -> 'ok'. -notice(Pid, Format, Args) -> - ?LOG_NOTICE(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_CONN}). - --spec warning(string()) -> 'ok'. -warning(Format) -> warning(Format, []). - --spec warning(string(), [any()]) -> 'ok'. -warning(Format, Args) -> warning(self(), Format, Args). - --spec warning(pid() | [tuple()], string(), [any()]) -> 'ok'. -warning(Pid, Format, Args) -> - ?LOG_WARNING(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_CONN}). - --spec error(string()) -> 'ok'. -error(Format) -> error(Format, []). - --spec error(string(), [any()]) -> 'ok'. -error(Format, Args) -> error(self(), Format, Args). - --spec error(pid() | [tuple()], string(), [any()]) -> 'ok'. -error(Pid, Format, Args) -> - ?LOG_ERROR(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_CONN}). - --spec critical(string()) -> 'ok'. -critical(Format) -> critical(Format, []). - --spec critical(string(), [any()]) -> 'ok'. -critical(Format, Args) -> critical(self(), Format, Args). - --spec critical(pid() | [tuple()], string(), [any()]) -> 'ok'. -critical(Pid, Format, Args) -> - ?LOG_CRITICAL(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_CONN}). - --spec alert(string()) -> 'ok'. -alert(Format) -> alert(Format, []). - --spec alert(string(), [any()]) -> 'ok'. -alert(Format, Args) -> alert(self(), Format, Args). - --spec alert(pid() | [tuple()], string(), [any()]) -> 'ok'. -alert(Pid, Format, Args) -> - ?LOG_ALERT(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_CONN}). - --spec emergency(string()) -> 'ok'. -emergency(Format) -> emergency(Format, []). - --spec emergency(string(), [any()]) -> 'ok'. -emergency(Format, Args) -> emergency(self(), Format, Args). - --spec emergency(pid() | [tuple()], string(), [any()]) -> 'ok'. -emergency(Pid, Format, Args) -> - ?LOG_EMERGENCY(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_CONN}). - --spec none(string()) -> 'ok'. -none(_Format) -> ok. - --spec none(string(), [any()]) -> 'ok'. -none(_Format, _Args) -> ok. - --spec none(pid() | [tuple()], string(), [any()]) -> 'ok'. -none(_Pid, _Format, _Args) -> ok. diff --git a/deps/rabbit/src/rabbit_reader.erl b/deps/rabbit/src/rabbit_reader.erl index 78e37a1b90fc..a756ac5df75b 100644 --- a/deps/rabbit/src/rabbit_reader.erl +++ b/deps/rabbit/src/rabbit_reader.erl @@ -44,6 +44,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include("rabbit_amqp_metrics.hrl"). -include_lib("kernel/include/logger.hrl"). +-include_lib("rabbit_common/include/logging.hrl"). -export([start_link/2, info/2, force_event_refresh/2, shutdown/2]). @@ -158,6 +159,7 @@ shutdown(Pid, Explanation) -> -spec init(pid(), {pid(), pid()}, ranch:ref()) -> no_return(). init(Parent, HelperSups, Ref) -> + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_CONN}), ?LG_PROCESS_TYPE(reader), {ok, Sock} = rabbit_networking:handshake(Ref, application:get_env(rabbit, proxy_protocol, false), @@ -254,7 +256,7 @@ server_capabilities(_) -> %%-------------------------------------------------------------------------- socket_error(Reason) when is_atom(Reason) -> - rabbit_log_connection:error("Error on AMQP connection ~tp: ~ts", + ?LOG_ERROR("Error on AMQP connection ~tp: ~ts", [self(), rabbit_misc:format_inet_error(Reason)]); socket_error(Reason) -> Fmt = "Error on AMQP connection ~tp:~n~tp", @@ -264,9 +266,9 @@ socket_error(Reason) -> %% This is presumably a TCP healthcheck, so don't log %% it unless specified otherwise. {ssl_upgrade_error, closed} -> - rabbit_log_connection:debug(Fmt, Args); + ?LOG_DEBUG(Fmt, Args); _ -> - rabbit_log_connection:error(Fmt, Args) + ?LOG_ERROR(Fmt, Args) end. inet_op(F) -> rabbit_misc:throw_on_error(inet_error, F). @@ -348,13 +350,13 @@ start_connection(Parent, HelperSups, RanchRef, Deb, Sock) -> connected_at = ConnectedAt0}} -> ConnName = dynamic_connection_name(Name), ConnDuration = connection_duration(ConnectedAt0), - rabbit_log_connection:info("closing AMQP connection (~ts, vhost: '~ts', user: '~ts', duration: '~ts')", + ?LOG_INFO("closing AMQP connection (~ts, vhost: '~ts', user: '~ts', duration: '~ts')", [ConnName, VHost, Username, ConnDuration]); %% just to be more defensive _ -> ConnName = dynamic_connection_name(Name), ConnDuration = connection_duration(ConnectedAt), - rabbit_log_connection:info("closing AMQP connection (~ts, duration: '~ts')", + ?LOG_INFO("closing AMQP connection (~ts, duration: '~ts')", [ConnName, ConnDuration]) end catch @@ -461,9 +463,9 @@ log_connection_exception(Severity, Name, Duration, Ex) -> log_connection_exception_with_severity(Severity, Fmt, Args) -> case Severity of - debug -> rabbit_log_connection:debug(Fmt, Args); - warning -> rabbit_log_connection:warning(Fmt, Args); - error -> rabbit_log_connection:error(Fmt, Args) + debug -> ?LOG_DEBUG(Fmt, Args); + warning -> ?LOG_WARNING(Fmt, Args); + error -> ?LOG_ERROR(Fmt, Args) end. run({M, F, A}) -> @@ -519,8 +521,8 @@ mainloop(Deb, Buf, BufLen, State = #v1{sock = Sock, Fmt = "accepting AMQP connection ~ts", Args = [ConnName], case Recv of - closed -> _ = rabbit_log_connection:debug(Fmt, Args); - _ -> _ = rabbit_log_connection:info(Fmt, Args) + closed -> _ = ?LOG_DEBUG(Fmt, Args); + _ -> _ = ?LOG_INFO(Fmt, Args) end; _ -> ok @@ -793,7 +795,7 @@ wait_for_channel_termination(N, TimerRef, {_, controlled} -> wait_for_channel_termination(N-1, TimerRef, State1); {_, uncontrolled} -> - rabbit_log_connection:error( + ?LOG_ERROR( "Error on AMQP connection ~tp (~ts, vhost: '~ts'," " user: '~ts', state: ~tp), channel ~tp:" "error while terminating:~n~tp", @@ -835,7 +837,7 @@ log_hard_error(#v1{connection_state = CS, log_name = ConnName, user = User, vhost = VHost}}, Channel, Reason) -> - rabbit_log_connection:error( + ?LOG_ERROR( "Error on AMQP connection ~tp (~ts, vhost: '~ts'," " user: '~ts', state: ~tp), channel ~tp:~n ~ts", [self(), ConnName, VHost, User#user.username, CS, Channel, format_hard_error(Reason)]). @@ -855,7 +857,7 @@ handle_exception(State = #v1{connection = #connection{protocol = Protocol, connection_state = starting}, Channel, Reason = #amqp_error{name = access_refused, explanation = ErrMsg}) -> - rabbit_log_connection:error( + ?LOG_ERROR( "Error on AMQP connection ~tp (~ts, state: ~tp):~n~ts", [self(), ConnName, starting, ErrMsg]), %% respect authentication failure notification capability @@ -874,7 +876,7 @@ handle_exception(State = #v1{connection = #connection{protocol = Protocol, connection_state = opening}, Channel, Reason = #amqp_error{name = not_allowed, explanation = ErrMsg}) -> - rabbit_log_connection:error( + ?LOG_ERROR( "Error on AMQP connection ~tp (~ts, user: '~ts', state: ~tp):~n~ts", [self(), ConnName, User#user.username, opening, ErrMsg]), send_error_on_channel0_and_close(Channel, Protocol, Reason, State); @@ -891,7 +893,7 @@ handle_exception(State = #v1{connection = #connection{protocol = Protocol, connection_state = tuning}, Channel, Reason = #amqp_error{name = not_allowed, explanation = ErrMsg}) -> - rabbit_log_connection:error( + ?LOG_ERROR( "Error on AMQP connection ~tp (~ts," " user: '~ts', state: ~tp):~n~ts", [self(), ConnName, User#user.username, tuning, ErrMsg]), @@ -1326,7 +1328,7 @@ handle_method0(#'connection.open'{virtual_host = VHost}, Infos), rabbit_event:notify(connection_created, Infos), maybe_emit_stats(State1), - rabbit_log_connection:info( + ?LOG_INFO( "connection ~ts: user '~ts' authenticated and granted access to vhost '~ts'", [dynamic_connection_name(ConnName), Username, VHost]), State1; @@ -1351,7 +1353,7 @@ handle_method0(#'connection.update_secret'{new_secret = NewSecret, reason = Reas user = User = #user{username = Username}, log_name = ConnName} = Conn, sock = Sock}) when ?IS_RUNNING(State) -> - rabbit_log_connection:debug( + ?LOG_DEBUG( "connection ~ts of user '~ts': " "asked to update secret, reason: ~ts", [dynamic_connection_name(ConnName), Username, Reason]), @@ -1368,16 +1370,16 @@ handle_method0(#'connection.update_secret'{new_secret = NewSecret, reason = Reas _ = rabbit_channel:update_user_state(Ch, User1) end, all_channels()), ok = send_on_channel0(Sock, #'connection.update_secret_ok'{}, Protocol), - rabbit_log_connection:info( + ?LOG_INFO( "connection ~ts: user '~ts' updated secret, reason: ~ts", [dynamic_connection_name(ConnName), Username, Reason]), State#v1{connection = Conn#connection{user = User1}}; {refused, Message} -> - rabbit_log_connection:error("Secret update was refused for user '~ts': ~tp", + ?LOG_ERROR("Secret update was refused for user '~ts': ~tp", [Username, Message]), rabbit_misc:protocol_error(not_allowed, "New secret was refused by one of the backends", []); {error, Message} -> - rabbit_log_connection:error("Secret update for user '~ts' failed: ~tp", + ?LOG_ERROR("Secret update for user '~ts' failed: ~tp", [Username, Message]), rabbit_misc:protocol_error(not_allowed, "Secret update failed", []) @@ -1839,7 +1841,7 @@ augment_connection_log_name(#connection{name = Name} = Connection) -> Connection; UserSpecifiedName -> LogName = <>, - rabbit_log_connection:info("connection ~ts has a client-provided name: ~ts", + ?LOG_INFO("connection ~ts has a client-provided name: ~ts", [Name, UserSpecifiedName]), ?store_proc_name(LogName), Connection#connection{log_name = LogName} diff --git a/deps/rabbitmq_stomp/src/rabbit_stomp_reader.erl b/deps/rabbitmq_stomp/src/rabbit_stomp_reader.erl index 7f377f45b1ff..a3e5b72dc697 100644 --- a/deps/rabbitmq_stomp/src/rabbit_stomp_reader.erl +++ b/deps/rabbitmq_stomp/src/rabbit_stomp_reader.erl @@ -19,6 +19,9 @@ -include("rabbit_stomp.hrl"). -include("rabbit_stomp_frame.hrl"). -include_lib("amqp_client/include/amqp_client.hrl"). +-include_lib("rabbit_common/include/logging.hrl"). +-include_lib("kernel/include/logger.hrl"). + -define(SIMPLE_METRICS, [pid, recv_oct, send_oct, reductions]). -define(OTHER_METRICS, [recv_cnt, send_cnt, send_pend, garbage_collection, state, @@ -62,6 +65,7 @@ close_connection(Pid, Reason) -> init([SupHelperPid, Ref, Configuration]) -> + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_CONN}), process_flag(trap_exit, true), {ok, Sock} = rabbit_networking:handshake(Ref, application:get_env(rabbitmq_stomp, proxy_protocol, false)), @@ -74,7 +78,7 @@ init([SupHelperPid, Ref, Configuration]) -> ProcState = rabbit_stomp_processor:initial_state(Configuration, ProcInitArgs), - rabbit_log_connection:info("accepting STOMP connection ~tp (~ts)", + ?LOG_INFO("accepting STOMP connection ~tp (~ts)", [self(), ConnName]), ParseState = rabbit_stomp_frame:initial_state(), @@ -334,7 +338,7 @@ code_change(_OldVsn, State, _Extra) -> log_reason({network_error, {ssl_upgrade_error, closed}, ConnName}, _State) -> - rabbit_log_connection:error("STOMP detected TLS upgrade error on ~ts: connection closed", + ?LOG_ERROR("STOMP detected TLS upgrade error on ~ts: connection closed", [ConnName]); @@ -355,46 +359,46 @@ log_reason({network_error, {tls_alert, Alert}}, ConnName}, _State) -> log_tls_alert(Alert, ConnName); log_reason({network_error, {ssl_upgrade_error, Reason}, ConnName}, _State) -> - rabbit_log_connection:error("STOMP detected TLS upgrade error on ~ts: ~tp", + ?LOG_ERROR("STOMP detected TLS upgrade error on ~ts: ~tp", [ConnName, Reason]); log_reason({network_error, Reason, ConnName}, _State) -> - rabbit_log_connection:error("STOMP detected network error on ~ts: ~tp", + ?LOG_ERROR("STOMP detected network error on ~ts: ~tp", [ConnName, Reason]); log_reason({network_error, Reason}, _State) -> - rabbit_log_connection:error("STOMP detected network error: ~tp", [Reason]); + ?LOG_ERROR("STOMP detected network error: ~tp", [Reason]); log_reason({shutdown, client_heartbeat_timeout}, #reader_state{ processor_state = ProcState }) -> AdapterName = rabbit_stomp_processor:adapter_name(ProcState), - rabbit_log_connection:warning("STOMP detected missed client heartbeat(s) " + ?LOG_WARNING("STOMP detected missed client heartbeat(s) " "on connection ~ts, closing it", [AdapterName]); log_reason({shutdown, {server_initiated_close, Reason}}, #reader_state{conn_name = ConnName}) -> - rabbit_log_connection:info("closing STOMP connection ~tp (~ts), reason: ~ts", + ?LOG_INFO("closing STOMP connection ~tp (~ts), reason: ~ts", [self(), ConnName, Reason]); log_reason(normal, #reader_state{conn_name = ConnName}) -> - rabbit_log_connection:info("closing STOMP connection ~tp (~ts)", [self(), ConnName]); + ?LOG_INFO("closing STOMP connection ~tp (~ts)", [self(), ConnName]); log_reason(shutdown, undefined) -> - rabbit_log_connection:error("closing STOMP connection that never completed connection handshake (negotiation)"); + ?LOG_ERROR("closing STOMP connection that never completed connection handshake (negotiation)"); log_reason(Reason, #reader_state{processor_state = ProcState}) -> AdapterName = rabbit_stomp_processor:adapter_name(ProcState), - rabbit_log_connection:warning("STOMP connection ~ts terminated" + ?LOG_WARNING("STOMP connection ~ts terminated" " with reason ~tp, closing it", [AdapterName, Reason]). log_tls_alert(handshake_failure, ConnName) -> - rabbit_log_connection:error("STOMP detected TLS upgrade error on ~ts: handshake failure", + ?LOG_ERROR("STOMP detected TLS upgrade error on ~ts: handshake failure", [ConnName]); log_tls_alert(unknown_ca, ConnName) -> - rabbit_log_connection:error("STOMP detected TLS certificate verification error on ~ts: alert 'unknown CA'", + ?LOG_ERROR("STOMP detected TLS certificate verification error on ~ts: alert 'unknown CA'", [ConnName]); log_tls_alert(Alert, ConnName) -> - rabbit_log_connection:error("STOMP detected TLS upgrade error on ~ts: alert ~ts", + ?LOG_ERROR("STOMP detected TLS upgrade error on ~ts: alert ~ts", [ConnName, Alert]). diff --git a/deps/rabbitmq_stream/src/rabbit_stream_reader.erl b/deps/rabbitmq_stream/src/rabbit_stream_reader.erl index 0407bfe27e2f..bc2bf8d78b8f 100644 --- a/deps/rabbitmq_stream/src/rabbit_stream_reader.erl +++ b/deps/rabbitmq_stream/src/rabbit_stream_reader.erl @@ -25,6 +25,7 @@ -include_lib("rabbitmq_stream_common/include/rabbit_stream.hrl"). -include_lib("kernel/include/logger.hrl"). +-include_lib("rabbit_common/include/logging.hrl"). -record(statem_data, {transport :: module(), @@ -143,6 +144,7 @@ init([KeepaliveSup, heartbeat := Heartbeat, transport := ConnTransport}]) -> process_flag(trap_exit, true), + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_CONN}), {ok, Sock} = rabbit_networking:handshake(Ref, application:get_env(rabbitmq_stream, @@ -220,7 +222,7 @@ init([KeepaliveSup, config = Config}); {Error, Reason} -> rabbit_net:fast_close(RealSocket), - rabbit_log_connection:warning("Closing connection because of ~tp ~tp", + ?LOG_WARNING("Closing connection because of ~tp ~tp", [Error, Reason]) end. @@ -411,7 +413,7 @@ tuned({call, From}, {info, _Items}, _StateData) -> {keep_state_and_data, {reply, From, []}}. state_timeout(State, Transport, Socket) -> - rabbit_log_connection:warning("Closing connection because of timeout in state " + ?LOG_WARNING("Closing connection because of timeout in state " "'~ts' likely due to lack of client action.", [State]), close_immediately(Transport, Socket), @@ -438,16 +440,16 @@ handle_info(Msg, setopts(Transport, S, [{active, once}]), #stream_connection{connection_step = NewConnectionStep} = Connection1, - rabbit_log_connection:debug("Transitioned from ~ts to ~ts", + ?LOG_DEBUG("Transitioned from ~ts to ~ts", [PreviousConnectionStep, NewConnectionStep]), Transition(NewConnectionStep, StatemData, Connection1, State1); {Closed, S} -> - rabbit_log_connection:debug("Stream protocol connection socket ~w closed", + ?LOG_DEBUG("Stream protocol connection socket ~w closed", [S]), stop; {Error, S, Reason} -> - rabbit_log_connection:warning("Socket error ~tp [~w]", [Reason, S]), + ?LOG_WARNING("Socket error ~tp [~w]", [Reason, S]), stop; {resource_alarm, IsThereAlarm} -> {keep_state, @@ -491,7 +493,7 @@ transition_to_opened(Transport, config = Configuration}}. invalid_transition(Transport, Socket, From, To) -> - rabbit_log_connection:warning("Closing socket ~w. Invalid transition from ~ts " + ?LOG_WARNING("Closing socket ~w. Invalid transition from ~ts " "to ~ts.", [Socket, From, To]), close_immediately(Transport, Socket), @@ -512,7 +514,7 @@ socket_op(Sock, Fun) -> {ok, Res} -> Res; {error, Reason} -> - rabbit_log_connection:warning("Error during socket operation ~tp", + ?LOG_WARNING("Error during socket operation ~tp", [Reason]), rabbit_net:fast_close(RealSocket), exit(normal) @@ -636,7 +638,7 @@ open(info, {resource_alarm, IsThereAlarm}, #configuration{credits_required_for_unblocking = CreditsRequiredForUnblocking}} = StatemData) -> - rabbit_log_connection:debug("Connection ~tp received resource alarm. Alarm " + ?LOG_DEBUG("Connection ~tp received resource alarm. Alarm " "on? ~tp", [ConnectionName, IsThereAlarm]), EnoughCreditsToUnblock = @@ -648,18 +650,18 @@ open(info, {resource_alarm, IsThereAlarm}, {false, EnoughCredits} -> not EnoughCredits end, - rabbit_log_connection:debug("Connection ~tp had blocked status set to ~tp, " + ?LOG_DEBUG("Connection ~tp had blocked status set to ~tp, " "new blocked status is now ~tp", [ConnectionName, Blocked, NewBlockedState]), case {Blocked, NewBlockedState} of {true, false} -> setopts(Transport, S, [{active, once}]), ok = rabbit_heartbeat:resume_monitor(Heartbeater), - rabbit_log_connection:debug("Unblocking connection ~tp", + ?LOG_DEBUG("Unblocking connection ~tp", [ConnectionName]); {false, true} -> ok = rabbit_heartbeat:pause_monitor(Heartbeater), - rabbit_log_connection:debug("Blocking connection ~tp after resource alarm", + ?LOG_DEBUG("Blocking connection ~tp after resource alarm", [ConnectionName]); _ -> ok @@ -690,7 +692,7 @@ open(info, {OK, S, Data}, closing -> stop; close_sent -> - rabbit_log_connection:debug("Transitioned to close_sent"), + ?LOG_DEBUG("Transitioned to close_sent"), setopts(Transport, S, [{active, once}]), {next_state, close_sent, StatemData#statem_data{connection = Connection1, @@ -814,14 +816,14 @@ open(info, open(info, {Closed, Socket}, #statem_data{connection = Connection}) when Closed =:= tcp_closed; Closed =:= ssl_closed -> _ = demonitor_all_streams(Connection), - rabbit_log_connection:warning("Stream reader socket ~w closed [~w]", + ?LOG_WARNING("Stream reader socket ~w closed [~w]", [Socket, self()]), stop; open(info, {Error, Socket, Reason}, #statem_data{connection = Connection}) when Error =:= tcp_error; Error =:= ssl_error -> _ = demonitor_all_streams(Connection), - rabbit_log_connection:error("Stream reader socket error ~tp [~w] [~w]", + ?LOG_ERROR("Stream reader socket error ~tp [~w] [~w]", [Reason, Socket, self()]), stop; open(info, {'DOWN', MonitorRef, process, _OsirisPid, _Reason}, @@ -864,14 +866,14 @@ open(info, heartbeat_send, ok -> keep_state_and_data; Unexpected -> - rabbit_log_connection:info("Heartbeat send error ~tp, closing connection", + ?LOG_INFO("Heartbeat send error ~tp, closing connection", [Unexpected]), _C1 = demonitor_all_streams(Connection), stop end; open(info, heartbeat_timeout, #statem_data{connection = #stream_connection{} = Connection}) -> - rabbit_log_connection:debug("Heartbeat timeout, closing connection"), + ?LOG_DEBUG("Heartbeat timeout, closing connection"), _C1 = demonitor_all_streams(Connection), stop; open(info, {infos, From}, @@ -906,7 +908,7 @@ open(info, check_outstanding_requests, end, false, Requests), case HasTimedOut of true -> - rabbit_log_connection:info("Forcing stream connection ~tp closing: request to client timed out", + ?LOG_INFO("Forcing stream connection ~tp closing: request to client timed out", [self()]), _ = demonitor_all_streams(Connection0), {stop, {request_timeout, <<"Request timeout">>}}; @@ -918,19 +920,19 @@ open(info, check_outstanding_requests, end; open(info, token_expired, #statem_data{connection = Connection}) -> _ = demonitor_all_streams(Connection), - rabbit_log_connection:info("Forcing stream connection ~tp closing because token expired", + ?LOG_INFO("Forcing stream connection ~tp closing because token expired", [self()]), {stop, {shutdown, <<"Token expired">>}}; open(info, {shutdown, Explanation} = Reason, #statem_data{connection = Connection}) -> %% rabbitmq_management or rabbitmq_stream_management plugin %% requests to close connection. - rabbit_log_connection:info("Forcing stream connection ~tp closing: ~tp", + ?LOG_INFO("Forcing stream connection ~tp closing: ~tp", [self(), Explanation]), _ = demonitor_all_streams(Connection), {stop, Reason}; open(info, Unknown, _StatemData) -> - rabbit_log_connection:warning("Received unknown message ~tp in state ~ts", + ?LOG_WARNING("Received unknown message ~tp in state ~ts", [Unknown, ?FUNCTION_NAME]), %% FIXME send close keep_state_and_data; @@ -1104,12 +1106,12 @@ open(cast, SendFileOct) of {error, closed} -> - rabbit_log_connection:info("Stream protocol connection has been closed by " + ?LOG_INFO("Stream protocol connection has been closed by " "peer", []), throw({stop, normal}); {error, Reason} -> - rabbit_log_connection:info("Error while sending chunks: ~tp", + ?LOG_INFO("Error while sending chunks: ~tp", [Reason]), %% likely a connection problem Consumer; @@ -1149,7 +1151,7 @@ close_sent(enter, _OldState, StateTimeout}}) -> {keep_state_and_data, {state_timeout, StateTimeout, close}}; close_sent(state_timeout, close, #statem_data{}) -> - rabbit_log_connection:warning("Closing connection because of timeout in state " + ?LOG_WARNING("Closing connection because of timeout in state " "'~ts' likely due to lack of client action.", [?FUNCTION_NAME]), stop; @@ -1162,7 +1164,7 @@ close_sent(info, {tcp, S, Data}, {Connection1, State1} = handle_inbound_data_post_close(Transport, Connection, State, Data), #stream_connection{connection_step = Step} = Connection1, - rabbit_log_connection:debug("Stream reader has transitioned from ~ts to ~ts", + ?LOG_DEBUG("Stream reader has transitioned from ~ts to ~ts", [?FUNCTION_NAME, Step]), case Step of closing_done -> @@ -1174,11 +1176,11 @@ close_sent(info, {tcp, S, Data}, connection_state = State1}} end; close_sent(info, {tcp_closed, S}, _StatemData) -> - rabbit_log_connection:debug("Stream protocol connection socket ~w closed [~w]", + ?LOG_DEBUG("Stream protocol connection socket ~w closed [~w]", [S, self()]), stop; close_sent(info, {tcp_error, S, Reason}, #statem_data{}) -> - rabbit_log_connection:error("Stream protocol connection socket error: ~tp " + ?LOG_ERROR("Stream protocol connection socket error: ~tp " "[~w] [~w]", [Reason, S, self()]), stop; @@ -1192,7 +1194,7 @@ close_sent(info, {resource_alarm, IsThereAlarm}, Connection#stream_connection{resource_alarm = IsThereAlarm}}}; close_sent(info, Msg, _StatemData) -> - rabbit_log_connection:warning("Ignored unknown message ~tp in state ~ts", + ?LOG_WARNING("Ignored unknown message ~tp in state ~ts", [Msg, ?FUNCTION_NAME]), keep_state_and_data; close_sent({call, From}, {info, _Items}, _StateData) -> @@ -1340,7 +1342,7 @@ handle_frame_pre_auth(Transport, Username, stream), auth_fail(Username, Msg, Args, C1, State), - rabbit_log_connection:warning(Msg, Args), + ?LOG_WARNING(Msg, Args), silent_close_delay(), {C1#stream_connection{connection_step = failure}, {sasl_authenticate, @@ -1356,7 +1358,7 @@ handle_frame_pre_auth(Transport, Args)}], C1, State), - rabbit_log_connection:warning(Msg, Args), + ?LOG_WARNING(Msg, Args), {C1#stream_connection{connection_step = failure}, {sasl_authenticate, ?RESPONSE_SASL_ERROR, <<>>}}; {challenge, Challenge, AuthState1} -> @@ -1387,7 +1389,7 @@ handle_frame_pre_auth(Transport, rabbit_core_metrics:auth_attempt_failed(Host, Username, stream), - rabbit_log_connection:warning("User '~ts' can only connect via localhost", + ?LOG_WARNING("User '~ts' can only connect via localhost", [Username]), {C1#stream_connection{connection_step = failure}, @@ -1424,7 +1426,7 @@ handle_frame_pre_auth(_Transport, Connection, #stream_connection_state{blocked = Blocked} = State, {tune, FrameMax, Heartbeat}) -> - rabbit_log_connection:debug("Tuning response ~tp ~tp ", + ?LOG_DEBUG("Tuning response ~tp ~tp ", [FrameMax, Heartbeat]), Parent = self(), %% sending a message to the main process so the heartbeat frame is sent from this main process @@ -1521,7 +1523,7 @@ handle_frame_pre_auth(_Transport, Connection, State, heartbeat) -> ?LOG_DEBUG("Received heartbeat frame pre auth"), {Connection, State}; handle_frame_pre_auth(_Transport, Connection, State, Command) -> - rabbit_log_connection:warning("unknown command ~w, closing connection.", + ?LOG_WARNING("unknown command ~w, closing connection.", [Command]), {Connection#stream_connection{connection_step = failure}, State}. @@ -1565,7 +1567,7 @@ handle_frame_post_auth(Transport, PublisherId, _WriterRef, Stream}}) -> - rabbit_log_connection:info("Cannot create publisher ~tp on stream ~tp, connection " + ?LOG_INFO("Cannot create publisher ~tp on stream ~tp, connection " "is blocked because of resource alarm", [PublisherId, Stream]), response(Transport, @@ -1598,7 +1600,7 @@ handle_frame_post_auth(Transport, NewUsername, stream), auth_fail(NewUsername, Msg, Args, C1, S1), - rabbit_log_connection:warning(Msg, Args), + ?LOG_WARNING(Msg, Args), {C1#stream_connection{connection_step = failure}, {sasl_authenticate, ?RESPONSE_AUTHENTICATION_FAILURE, <<>>}}; @@ -1613,7 +1615,7 @@ handle_frame_post_auth(Transport, Args)}], C1, S1), - rabbit_log_connection:warning(Msg, Args), + ?LOG_WARNING(Msg, Args), {C1#stream_connection{connection_step = failure}, {sasl_authenticate, ?RESPONSE_SASL_ERROR, <<>>}}; {challenge, Challenge, AuthState1} -> @@ -1642,7 +1644,7 @@ handle_frame_post_auth(Transport, rabbit_core_metrics:auth_attempt_failed(Host, Username, stream), - rabbit_log_connection:warning("Not allowed to change username '~ts'. Only password", + ?LOG_WARNING("Not allowed to change username '~ts'. Only password", [Username]), {C1#stream_connection{connection_step = failure}, @@ -1663,7 +1665,7 @@ handle_frame_post_auth(Transport, {C2, S1} end; {OtherMechanism, _} -> - rabbit_log_connection:warning("User '~ts' cannot change initial auth mechanism '~ts' for '~ts'", + ?LOG_WARNING("User '~ts' cannot change initial auth mechanism '~ts' for '~ts'", [Username, NewMechanism, OtherMechanism]), CmdBody = {sasl_authenticate, ?RESPONSE_SASL_CANNOT_CHANGE_MECHANISM, <<>>}, @@ -2056,7 +2058,7 @@ handle_frame_post_auth(Transport, SendFileOct) of {error, closed} -> - rabbit_log_connection:info("Stream protocol connection has been closed by " + ?LOG_INFO("Stream protocol connection has been closed by " "peer", []), throw({stop, normal}); @@ -2516,12 +2518,12 @@ handle_frame_post_auth(Transport, SendFileOct) of {error, closed} -> - rabbit_log_connection:info("Stream protocol connection has been closed by " + ?LOG_INFO("Stream protocol connection has been closed by " "peer", []), throw({stop, normal}); {error, Reason} -> - rabbit_log_connection:info("Error while sending chunks: ~tp", + ?LOG_INFO("Error while sending chunks: ~tp", [Reason]), %% likely a connection problem Consumer; @@ -2850,7 +2852,7 @@ maybe_dispatch_on_subscription(Transport, SendFileOct) of {error, closed} -> - rabbit_log_connection:info("Stream protocol connection has been closed by " + ?LOG_INFO("Stream protocol connection has been closed by " "peer", []), throw({stop, normal}); @@ -3228,13 +3230,13 @@ handle_frame_post_close(_Transport, Connection, State, {response, _CorrelationId, {close, _Code}}) -> - rabbit_log_connection:info("Received close confirmation from client"), + ?LOG_INFO("Received close confirmation from client"), {Connection#stream_connection{connection_step = closing_done}, State}; handle_frame_post_close(_Transport, Connection, State, heartbeat) -> - rabbit_log_connection:debug("Received heartbeat command post close"), + ?LOG_DEBUG("Received heartbeat command post close"), {Connection, State}; handle_frame_post_close(_Transport, Connection, State, Command) -> - rabbit_log_connection:warning("ignored command on close ~tp .", + ?LOG_WARNING("ignored command on close ~tp .", [Command]), {Connection, State}. diff --git a/deps/rabbitmq_web_stomp/src/rabbit_web_stomp_handler.erl b/deps/rabbitmq_web_stomp/src/rabbit_web_stomp_handler.erl index 5f98feaf25a2..01abbb7da356 100644 --- a/deps/rabbitmq_web_stomp/src/rabbit_web_stomp_handler.erl +++ b/deps/rabbitmq_web_stomp/src/rabbit_web_stomp_handler.erl @@ -13,6 +13,7 @@ -include_lib("rabbitmq_stomp/include/rabbit_stomp.hrl"). -include_lib("rabbitmq_stomp/include/rabbit_stomp_frame.hrl"). -include_lib("amqp_client/include/amqp_client.hrl"). +-include_lib("rabbit_common/include/logging.hrl"). %% Websocket. -export([ @@ -68,6 +69,7 @@ takeover(Parent, Ref, Socket, Transport, Opts, Buffer, {Handler, HandlerState}) %% Websocket. init(Req0, Opts) -> + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_CONN}), {PeerAddr, _PeerPort} = maps:get(peer, Req0), {_, KeepaliveSup} = lists:keyfind(keepalive_sup, 1, Opts), SockInfo = maps:get(proxy_header, Req0, undefined), @@ -105,7 +107,7 @@ websocket_init(State) -> -spec close_connection(pid(), string()) -> 'ok'. close_connection(Pid, Reason) -> - rabbit_log_connection:info("Web STOMP: will terminate connection process ~tp, reason: ~ts", + ?LOG_INFO("Web STOMP: will terminate connection process ~tp, reason: ~ts", [Pid, Reason]), sys:terminate(Pid, Reason), ok. @@ -242,7 +244,7 @@ websocket_info(emit_stats, State) -> {ok, emit_stats(State)}; websocket_info(Msg, State) -> - rabbit_log_connection:info("Web STOMP: unexpected message ~tp", + ?LOG_INFO("Web STOMP: unexpected message ~tp", [Msg]), {ok, State}. @@ -274,7 +276,7 @@ handle_data(Data, State0) -> {[{active, false}], State1}; {error, Error0} -> Error1 = rabbit_misc:format("~tp", [Error0]), - rabbit_log_connection:error("STOMP detected framing error '~ts'", [Error1]), + ?LOG_ERROR("STOMP detected framing error '~ts'", [Error1]), stop(State0, 1007, Error1); Other -> Other diff --git a/deps/rabbitmq_web_stomp/src/rabbit_web_stomp_listener.erl b/deps/rabbitmq_web_stomp/src/rabbit_web_stomp_listener.erl index 14cf68e795a6..becaf8c564dc 100644 --- a/deps/rabbitmq_web_stomp/src/rabbit_web_stomp_listener.erl +++ b/deps/rabbitmq_web_stomp/src/rabbit_web_stomp_listener.erl @@ -1,4 +1,4 @@ -%% This Source Code Form is subject to the terms of the Mozilla Public + %% License, v. 2.0. If a copy of the MPL was not distributed with this %% file, You can obtain one at https://mozilla.org/MPL/2.0/. %% @@ -14,6 +14,9 @@ close_all_client_connections/1 ]). +-include_lib("kernel/include/logger.hrl"). +-include_lib("rabbit_common/include/logging.hrl"). + %% for testing purposes -export([get_binding_address/1, get_tcp_port/1, get_tcp_conf/2]). @@ -28,6 +31,7 @@ -spec init() -> ok. init() -> + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_CONN}), WsFrame = get_env(ws_frame, text), CowboyOpts0 = maps:from_list(get_env(cowboy_opts, [])), CowboyOpts = CowboyOpts0#{proxy_header => get_env(proxy_protocol, false), @@ -111,14 +115,14 @@ start_tcp_listener(TCPConf0, CowboyOpts0, Routes) -> {ok, _} -> ok; {error, {already_started, _}} -> ok; {error, ErrTCP} -> - rabbit_log_connection:error( + ?LOG_ERROR( "Failed to start a WebSocket (HTTP) listener. Error: ~tp," " listener settings: ~tp", [ErrTCP, TCPConf]), throw(ErrTCP) end, listener_started(?TCP_PROTOCOL, TCPConf), - rabbit_log_connection:info( + ?LOG_INFO( "rabbit_web_stomp: listening for HTTP connections on ~ts:~w", [get_binding_address(TCPConf), Port]). @@ -150,14 +154,14 @@ start_tls_listener(TLSConf0, CowboyOpts0, Routes) -> {ok, _} -> ok; {error, {already_started, _}} -> ok; {error, ErrTLS} -> - rabbit_log_connection:error( + ?LOG_ERROR( "Failed to start a TLS WebSocket (HTTPS) listener. Error: ~tp," " listener settings: ~tp", [ErrTLS, TLSConf]), throw(ErrTLS) end, listener_started(?TLS_PROTOCOL, TLSConf), - rabbit_log_connection:info( + ?LOG_INFO( "rabbit_web_stomp: listening for HTTPS connections on ~ts:~w", [get_binding_address(TLSConf), TLSPort]). From ee100af9ebf4d20a517f57b8a85e9e6e824063c8 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Mon, 14 Jul 2025 11:32:13 +0200 Subject: [PATCH 10/31] [skip ci] Remove rabbit_log_ldad and use LOG_ macros --- .../src/rabbit_auth_backend_ldap.erl | 32 +++--- .../src/rabbit_auth_backend_ldap_app.erl | 9 +- .../src/rabbit_log_ldap.erl | 108 ------------------ 3 files changed, 23 insertions(+), 126 deletions(-) delete mode 100644 deps/rabbitmq_auth_backend_ldap/src/rabbit_log_ldap.erl diff --git a/deps/rabbitmq_auth_backend_ldap/src/rabbit_auth_backend_ldap.erl b/deps/rabbitmq_auth_backend_ldap/src/rabbit_auth_backend_ldap.erl index 0b8f3eb591d2..f18571accf8c 100644 --- a/deps/rabbitmq_auth_backend_ldap/src/rabbit_auth_backend_ldap.erl +++ b/deps/rabbitmq_auth_backend_ldap/src/rabbit_auth_backend_ldap.erl @@ -11,6 +11,8 @@ -include_lib("eldap/include/eldap.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). +-include_lib("kernel/include/logger.hrl"). +-include("logging.hrl"). -behaviour(rabbit_authn_backend). -behaviour(rabbit_authz_backend). @@ -514,18 +516,16 @@ with_ldap({ok, Creds}, Fun, Servers) -> Opts1 = case env(log) of network -> Pre = " LDAP network traffic: ", - rabbit_log_ldap:info( - " LDAP connecting to servers: ~tp", [Servers]), - [{log, fun(1, S, A) -> rabbit_log_ldap:warning(Pre ++ S, A); + ?LOG_INFO("LDAP connecting to servers: ~tp", [Servers]), + [{log, fun(1, S, A) -> ?LOG_WARNING(Pre ++ S, A); (2, S, A) -> - rabbit_log_ldap:info(Pre ++ S, scrub_creds(A, [])) + ?LOG_INFO(Pre ++ S, scrub_creds(A, [])) end} | Opts0]; network_unsafe -> Pre = " LDAP network traffic: ", - rabbit_log_ldap:info( - " LDAP connecting to servers: ~tp", [Servers]), - [{log, fun(1, S, A) -> rabbit_log_ldap:warning(Pre ++ S, A); - (2, S, A) -> rabbit_log_ldap:info( Pre ++ S, A) + ?LOG_INFO(" LDAP connecting to servers: ~tp", [Servers]), + [{log, fun(1, S, A) -> ?LOG_WARNING(Pre ++ S, A); + (2, S, A) -> ?LOG_INFO( Pre ++ S, A) end} | Opts0]; _ -> Opts0 @@ -550,7 +550,7 @@ with_ldap({ok, Creds}, Fun, Servers) -> with_login(Creds, Servers, Opts, Fun) -> with_login(Creds, Servers, Opts, Fun, ?LDAP_OPERATION_RETRIES). with_login(_Creds, _Servers, _Opts, _Fun, 0 = _RetriesLeft) -> - rabbit_log_ldap:warning("LDAP failed to perform an operation. TCP connection to a LDAP server was closed or otherwise defunct. Exhausted all retries."), + ?LOG_WARNING("LDAP failed to perform an operation. TCP connection to a LDAP server was closed or otherwise defunct. Exhausted all retries."), {error, ldap_connect_error}; with_login(Creds, Servers, Opts, Fun, RetriesLeft) -> case get_or_create_conn(Creds == anon, Servers, Opts) of @@ -609,9 +609,9 @@ with_login(Creds, Servers, Opts, Fun, RetriesLeft) -> purge_connection(Creds, Servers, Opts) -> %% purge and retry with a new connection - rabbit_log_ldap:warning("TCP connection to a LDAP server was closed or otherwise defunct."), + ?LOG_WARNING("TCP connection to a LDAP server was closed or otherwise defunct."), purge_conn(Creds == anon, Servers, Opts), - rabbit_log_ldap:warning("LDAP will retry with a new connection."). + ?LOG_WARNING("LDAP will retry with a new connection."). call_ldap_fun(Fun, LDAP) -> call_ldap_fun(Fun, LDAP, ""). @@ -725,7 +725,7 @@ purge_conn(IsAnon, Servers, Opts) -> Conns = get(ldap_conns), Key = {IsAnon, Servers, Opts}, {ok, Conn} = maps:find(Key, Conns), - rabbit_log_ldap:warning("LDAP will purge an already closed or defunct LDAP server connection from the pool"), + ?LOG_WARNING("LDAP will purge an already closed or defunct LDAP server connection from the pool"), % We cannot close the connection with eldap:close/1 because as of OTP-13327 % eldap will try to do_unbind first and will fail with a `{gen_tcp_error, closed}`. % Since we know that the connection is already closed, we just @@ -770,7 +770,7 @@ ssl_options() -> Opts0 = rabbit_ssl_options:fix_client(env(ssl_options)), case env(ssl_hostname_verification, undefined) of wildcard -> - rabbit_log_ldap:debug("Enabling wildcard-aware hostname verification for LDAP client connections"), + ?LOG_DEBUG("Enabling wildcard-aware hostname verification for LDAP client connections"), %% Needed for non-HTTPS connections that connect to servers that use wildcard certificates. %% See https://erlang.org/doc/man/public_key.html#pkix_verify_hostname_match_fun-1. [{customize_hostname_check, [{match_fun, public_key:pkix_verify_hostname_match_fun(https)}]} | Opts0]; @@ -786,7 +786,7 @@ at_least(Ver) -> get_expected_env_str(Key, Default) -> V = case env(Key) of Default -> - rabbit_log_ldap:warning("rabbitmq_auth_backend_ldap configuration key '~tp' is set to " + ?LOG_WARNING("rabbitmq_auth_backend_ldap configuration key '~tp' is set to " "the default value of '~tp', expected to get a non-default value", [Key, Default]), Default; @@ -884,7 +884,7 @@ dn_lookup(Username, LDAP) -> ?L1("DN lookup: ~ts -> ~ts", [Username, DN]), DN; {ok, {eldap_search_result, Entries, _Referrals, _Controls}} -> - rabbit_log_ldap:warning("Searching for DN for ~ts, got back ~tp", + ?LOG_WARNING("Searching for DN for ~ts, got back ~tp", [Filled, Entries]), Filled; {error, _} = E -> @@ -963,7 +963,7 @@ is_dn(_S) -> false. log(Fmt, Args) -> case env(log) of false -> ok; - _ -> rabbit_log_ldap:info(Fmt ++ "", Args) + _ -> ?LOG_INFO(Fmt ++ "", Args) end. fill(Fmt, Args) -> diff --git a/deps/rabbitmq_auth_backend_ldap/src/rabbit_auth_backend_ldap_app.erl b/deps/rabbitmq_auth_backend_ldap/src/rabbit_auth_backend_ldap_app.erl index 806ed9378fc9..b441d7415f3a 100644 --- a/deps/rabbitmq_auth_backend_ldap/src/rabbit_auth_backend_ldap_app.erl +++ b/deps/rabbitmq_auth_backend_ldap/src/rabbit_auth_backend_ldap_app.erl @@ -10,6 +10,9 @@ -behaviour(application). -export([start/2, stop/1]). +-include_lib("kernel/include/logger.hrl"). +-include("logging.hrl"). + %% Dummy supervisor - see Ulf Wiger's comment at %% http://erlang.org/pipermail/erlang-questions/2010-April/050508.html -behaviour(supervisor). @@ -28,7 +31,7 @@ start(_Type, _StartArgs) -> {ok, Backends} = application:get_env(rabbit, auth_backends), case configured(rabbit_auth_backend_ldap, Backends) of true -> ok; - false -> rabbit_log_ldap:warning( + false -> ?LOG_WARNING( "LDAP plugin loaded, but rabbit_auth_backend_ldap is not " "in the list of auth_backends. LDAP auth will not work.") end, @@ -53,4 +56,6 @@ configured(M, [_ |T]) -> configured(M, T). %%---------------------------------------------------------------------------- -init([]) -> {ok, {{one_for_one, 3, 10}, []}}. +init([]) -> + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_LDAP}), + {ok, {{one_for_one, 3, 10}, []}}. diff --git a/deps/rabbitmq_auth_backend_ldap/src/rabbit_log_ldap.erl b/deps/rabbitmq_auth_backend_ldap/src/rabbit_log_ldap.erl deleted file mode 100644 index fe63a9bb23cd..000000000000 --- a/deps/rabbitmq_auth_backend_ldap/src/rabbit_log_ldap.erl +++ /dev/null @@ -1,108 +0,0 @@ -%% This Source Code Form is subject to the terms of the Mozilla Public -%% License, v. 2.0. If a copy of the MPL was not distributed with this -%% file, You can obtain one at https://mozilla.org/MPL/2.0/. -%% -%% Copyright (c) 2007-2025 Broadcom. All Rights Reserved. The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. All rights reserved. -%% - -%% @doc Compatibility module for the old Lager-based logging API. --module(rabbit_log_ldap). - --export([debug/1, debug/2, debug/3, - info/1, info/2, info/3, - notice/1, notice/2, notice/3, - warning/1, warning/2, warning/3, - error/1, error/2, error/3, - critical/1, critical/2, critical/3, - alert/1, alert/2, alert/3, - emergency/1, emergency/2, emergency/3, - none/1, none/2, none/3]). - --include("logging.hrl"). --include_lib("kernel/include/logger.hrl"). - --compile({no_auto_import, [error/2, error/3]}). - -%%---------------------------------------------------------------------------- - --spec debug(string()) -> 'ok'. --spec debug(string(), [any()]) -> 'ok'. --spec debug(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec info(string()) -> 'ok'. --spec info(string(), [any()]) -> 'ok'. --spec info(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec notice(string()) -> 'ok'. --spec notice(string(), [any()]) -> 'ok'. --spec notice(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec warning(string()) -> 'ok'. --spec warning(string(), [any()]) -> 'ok'. --spec warning(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec error(string()) -> 'ok'. --spec error(string(), [any()]) -> 'ok'. --spec error(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec critical(string()) -> 'ok'. --spec critical(string(), [any()]) -> 'ok'. --spec critical(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec alert(string()) -> 'ok'. --spec alert(string(), [any()]) -> 'ok'. --spec alert(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec emergency(string()) -> 'ok'. --spec emergency(string(), [any()]) -> 'ok'. --spec emergency(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec none(string()) -> 'ok'. --spec none(string(), [any()]) -> 'ok'. --spec none(pid() | [tuple()], string(), [any()]) -> 'ok'. - -%%---------------------------------------------------------------------------- - -debug(Format) -> debug(Format, []). -debug(Format, Args) -> debug(self(), Format, Args). -debug(Pid, Format, Args) -> - ?LOG_DEBUG(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_LDAP}). - -info(Format) -> info(Format, []). -info(Format, Args) -> info(self(), Format, Args). -info(Pid, Format, Args) -> - ?LOG_INFO(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_LDAP}). - -notice(Format) -> notice(Format, []). -notice(Format, Args) -> notice(self(), Format, Args). -notice(Pid, Format, Args) -> - ?LOG_NOTICE(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_LDAP}). - -warning(Format) -> warning(Format, []). -warning(Format, Args) -> warning(self(), Format, Args). -warning(Pid, Format, Args) -> - ?LOG_WARNING(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_LDAP}). - -error(Format) -> error(Format, []). -error(Format, Args) -> error(self(), Format, Args). -error(Pid, Format, Args) -> - ?LOG_ERROR(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_LDAP}). - -critical(Format) -> critical(Format, []). -critical(Format, Args) -> critical(self(), Format, Args). -critical(Pid, Format, Args) -> - ?LOG_CRITICAL(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_LDAP}). - -alert(Format) -> alert(Format, []). -alert(Format, Args) -> alert(self(), Format, Args). -alert(Pid, Format, Args) -> - ?LOG_ALERT(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_LDAP}). - -emergency(Format) -> emergency(Format, []). -emergency(Format, Args) -> emergency(self(), Format, Args). -emergency(Pid, Format, Args) -> - ?LOG_EMERGENCY(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_LDAP}). - -none(_Format) -> ok. -none(_Format, _Args) -> ok. -none(_Pid, _Format, _Args) -> ok. From ad15dd39df442c1aec55a0e3576a4bb827d4713c Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Mon, 14 Jul 2025 13:52:07 +0200 Subject: [PATCH 11/31] [skip ci] Simplify logging around peer discovery --- .../include/rabbit_peer_discovery.hrl | 2 - .../src/rabbit_peer_discovery_cleanup.erl | 37 +++++++---------- .../src/rabbit_peer_discovery_config.erl | 4 +- .../src/rabbit_peer_discovery_httpc.erl | 32 +++++++-------- .../src/rabbit_peer_discovery_util.erl | 20 +++++----- .../src/rabbit_peer_discovery_consul.erl | 40 +++++++++---------- 6 files changed, 62 insertions(+), 73 deletions(-) diff --git a/deps/rabbitmq_peer_discovery_common/include/rabbit_peer_discovery.hrl b/deps/rabbitmq_peer_discovery_common/include/rabbit_peer_discovery.hrl index 05e07d164adf..5560ea7e8f6d 100644 --- a/deps/rabbitmq_peer_discovery_common/include/rabbit_peer_discovery.hrl +++ b/deps/rabbitmq_peer_discovery_common/include/rabbit_peer_discovery.hrl @@ -7,8 +7,6 @@ -include_lib("rabbit_common/include/logging.hrl"). --define(RMQLOG_DOMAIN_PEER_DIS, ?DEFINE_RMQLOG_DOMAIN(peer_discovery)). - % rabbitmq/rabbitmq-peer-discovery-aws#25 % Note: this timeout must not be greater than the default % gen_server:call timeout of 5000ms. This `timeout`, diff --git a/deps/rabbitmq_peer_discovery_common/src/rabbit_peer_discovery_cleanup.erl b/deps/rabbitmq_peer_discovery_common/src/rabbit_peer_discovery_cleanup.erl index 9cbb5828b84a..5522867e82e6 100644 --- a/deps/rabbitmq_peer_discovery_common/src/rabbit_peer_discovery_cleanup.erl +++ b/deps/rabbitmq_peer_discovery_common/src/rabbit_peer_discovery_cleanup.erl @@ -84,12 +84,12 @@ check_cluster() -> {ok, State :: #state{}, timeout() | hibernate} | {stop, Reason :: term()} | ignore). init([]) -> + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_PEER_DISC}), Map = ?CONFIG_MODULE:config_map(?CONFIG_KEY), case map_size(Map) of 0 -> ?LOG_INFO( - "Peer discovery: node cleanup is disabled", - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + "Peer discovery: node cleanup is disabled"), {ok, #state{}}; _ -> Interval = ?CONFIG_MODULE:get(cleanup_interval, ?CONFIG_MAPPING, Map), @@ -103,8 +103,7 @@ init([]) -> end, ?LOG_INFO( "Peer discovery: enabling node cleanup (~ts). Check interval: ~tp seconds.", - [WarnMsg, State#state.interval], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + [WarnMsg, State#state.interval]), {ok, State} end. @@ -126,8 +125,7 @@ init([]) -> handle_call(check_cluster, _From, State) -> ?LOG_DEBUG( - "Peer discovery: checking for partitioned nodes to clean up.", - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + "Peer discovery: checking for partitioned nodes to clean up."), maybe_cleanup(State), {reply, ok, State}; handle_call(_Request, _From, State) -> @@ -236,26 +234,24 @@ maybe_cleanup(State) -> UnreachableNodes :: [node()]) -> ok. maybe_cleanup(_, []) -> ?LOG_DEBUG( - "Peer discovery: all known cluster nodes are up.", - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}); + "Peer discovery: all known cluster nodes are up."); + maybe_cleanup(State, UnreachableNodes) -> ?LOG_DEBUG( "Peer discovery: cleanup discovered unreachable nodes: ~tp", - [UnreachableNodes], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + [UnreachableNodes]), case lists:subtract(as_list(UnreachableNodes), as_list(service_discovery_nodes())) of [] -> ?LOG_DEBUG( "Peer discovery: all unreachable nodes are still " "registered with the discovery backend ~tp", [rabbit_peer_discovery:backend()], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), ok; Nodes -> ?LOG_DEBUG( "Peer discovery: unreachable nodes are not registered " - "with the discovery backend ~tp", [Nodes], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + "with the discovery backend ~tp", [Nodes]), maybe_remove_nodes(Nodes, State#state.warn_only) end. @@ -272,17 +268,14 @@ maybe_cleanup(State, UnreachableNodes) -> maybe_remove_nodes([], _) -> ok; maybe_remove_nodes([Node | Nodes], true) -> ?LOG_WARNING( - "Peer discovery: node ~ts is unreachable", [Node], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + "Peer discovery: node ~ts is unreachable", [Node]), maybe_remove_nodes(Nodes, true); maybe_remove_nodes([Node | Nodes], false) -> ?LOG_WARNING( - "Peer discovery: removing unknown node ~ts from the cluster", [Node], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + "Peer discovery: removing unknown node ~ts from the cluster", [Node]), _ = rabbit_db_cluster:forget_member(Node, false), ?LOG_WARNING( - "Peer discovery: removing all quorum queue replicas on node ~ts", [Node], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + "Peer discovery: removing all quorum queue replicas on node ~ts", [Node]), _ = rabbit_quorum_queue:shrink_all(Node), maybe_remove_nodes(Nodes, false). @@ -310,13 +303,11 @@ service_discovery_nodes() -> Nodes = as_list(OneOrMultipleNodes), ?LOG_DEBUG( "Peer discovery cleanup: ~tp returned ~tp", - [Module, Nodes], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + [Module, Nodes]), Nodes; {error, Reason} -> ?LOG_DEBUG( "Peer discovery cleanup: ~tp returned error ~tp", - [Module, Reason], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + [Module, Reason]), [] end. diff --git a/deps/rabbitmq_peer_discovery_common/src/rabbit_peer_discovery_config.erl b/deps/rabbitmq_peer_discovery_common/src/rabbit_peer_discovery_config.erl index cfd3896e5cbf..6089ead5f798 100644 --- a/deps/rabbitmq_peer_discovery_common/src/rabbit_peer_discovery_config.erl +++ b/deps/rabbitmq_peer_discovery_common/src/rabbit_peer_discovery_config.erl @@ -28,7 +28,7 @@ get(Key, Mapping, Config) -> ?LOG_ERROR( "Key ~ts is not found in peer discovery config mapping ~tp!", [Key, Mapping], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), throw({badkey, Key}); true -> get_with_entry_meta(Key, maps:get(Key, Mapping), Config) @@ -44,7 +44,7 @@ get_integer(Key, Mapping, Config) -> ?LOG_ERROR( "Key ~ts is not found in peer discovery config mapping ~tp!", [Key, Mapping], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), throw({badkey, Key}); true -> get_integer_with_entry_meta(Key, maps:get(Key, Mapping), Config) diff --git a/deps/rabbitmq_peer_discovery_common/src/rabbit_peer_discovery_httpc.erl b/deps/rabbitmq_peer_discovery_common/src/rabbit_peer_discovery_httpc.erl index 10d6af951ce4..016fab15d199 100644 --- a/deps/rabbitmq_peer_discovery_common/src/rabbit_peer_discovery_httpc.erl +++ b/deps/rabbitmq_peer_discovery_common/src/rabbit_peer_discovery_httpc.erl @@ -141,10 +141,10 @@ get(Scheme, Host, Port, Path, Args) -> %% get(Scheme, Host, Port, Path, Args, Headers, HttpOpts) -> URL = build_uri(Scheme, Host, Port, Path, Args), - ?LOG_DEBUG("GET ~ts", [URL], #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + ?LOG_DEBUG("GET ~ts", [URL], #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), HttpOpts1 = ensure_timeout(HttpOpts), Response = httpc:request(get, {URL, Headers}, HttpOpts1, []), - ?LOG_DEBUG("Response: ~tp", [Response], #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + ?LOG_DEBUG("Response: ~tp", [Response], #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), parse_response(Response). @@ -179,10 +179,10 @@ post(Scheme, Host, Port, Path, Args, Body) -> %% post(Scheme, Host, Port, Path, Args, Headers, HttpOpts, Body) -> URL = build_uri(Scheme, Host, Port, Path, Args), - ?LOG_DEBUG("POST ~ts [~tp]", [URL, Body], #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + ?LOG_DEBUG("POST ~ts [~tp]", [URL, Body], #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), HttpOpts1 = ensure_timeout(HttpOpts), Response = httpc:request(post, {URL, Headers, ?CONTENT_JSON, Body}, HttpOpts1, []), - ?LOG_DEBUG("Response: [~tp]", [Response], #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + ?LOG_DEBUG("Response: [~tp]", [Response], #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), parse_response(Response). @@ -208,10 +208,10 @@ post(Scheme, Host, Port, Path, Args, Headers, HttpOpts, Body) -> Body :: string() | binary() | tuple(). put(Scheme, Host, Port, Path, Args, Body) -> URL = build_uri(Scheme, Host, Port, Path, Args), - ?LOG_DEBUG("PUT ~ts [~tp]", [URL, Body], #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + ?LOG_DEBUG("PUT ~ts [~tp]", [URL, Body], #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), HttpOpts = ensure_timeout(), Response = httpc:request(put, {URL, [], ?CONTENT_URLENCODED, Body}, HttpOpts, []), - ?LOG_DEBUG("Response: [~tp]", [Response], #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + ?LOG_DEBUG("Response: [~tp]", [Response], #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), parse_response(Response). @@ -262,10 +262,10 @@ put(Scheme, Host, Port, Path, Args, Headers, Body) -> Body :: string() | binary() | tuple(). put(Scheme, Host, Port, Path, Args, Headers, HttpOpts, Body) -> URL = build_uri(Scheme, Host, Port, Path, Args), - ?LOG_DEBUG("PUT ~ts [~tp] [~tp]", [URL, Headers, Body], #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + ?LOG_DEBUG("PUT ~ts [~tp] [~tp]", [URL, Headers, Body], #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), HttpOpts1 = ensure_timeout(HttpOpts), Response = httpc:request(put, {URL, Headers, ?CONTENT_URLENCODED, Body}, HttpOpts1, []), - ?LOG_DEBUG("Response: [~tp]", [Response], #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + ?LOG_DEBUG("Response: [~tp]", [Response], #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), parse_response(Response). %% @public @@ -304,10 +304,10 @@ delete(Scheme, Host, Port, PathSegments, Args, HttpOpts, Body) when is_list(Path delete(Scheme, Host, Port, Path, Args, HttpOpts, Body); delete(Scheme, Host, Port, Path, Args, HttpOpts, Body) -> URL = build_uri(Scheme, Host, Port, Path, Args), - ?LOG_DEBUG("DELETE ~ts [~tp]", [URL, Body], #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + ?LOG_DEBUG("DELETE ~ts [~tp]", [URL, Body], #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), HttpOpts1 = ensure_timeout(HttpOpts), Response = httpc:request(delete, {URL, [], ?CONTENT_URLENCODED, Body}, HttpOpts1, []), - ?LOG_DEBUG("Response: [~tp]", [Response], #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + ?LOG_DEBUG("Response: [~tp]", [Response], #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), parse_response(Response). @@ -323,7 +323,7 @@ maybe_configure_proxy() -> 0 -> ?LOG_DEBUG( "HTTP client proxy is not configured", - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), ok; _ -> HttpProxy = ?CONFIG_MODULE:get(http_proxy, ?CONFIG_MAPPING, Map), @@ -332,7 +332,7 @@ maybe_configure_proxy() -> ?LOG_DEBUG( "Configured HTTP proxy: ~tp, HTTPS proxy: ~tp, exclusions: ~tp", [HttpProxy, HttpsProxy, ProxyExclusions], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), _ = maybe_set_proxy(proxy, HttpProxy, ProxyExclusions), _ = maybe_set_proxy(https_proxy, HttpsProxy, ProxyExclusions), ok @@ -368,7 +368,7 @@ maybe_set_proxy(Option, ProxyUrl, ProxyExclusions) -> ?LOG_DEBUG( "Configuring HTTP client's ~ts setting: ~tp, exclusions: ~tp", [Option, {Host, Port}, ProxyExclusions], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), httpc:set_option(Option, {{Host, Port}, ProxyExclusions}) end. @@ -415,7 +415,7 @@ decode_body(?CONTENT_JSON, Body) -> "HTTP client could not decode a JSON payload " "(JSON parser returned an error): ~tp.", [Err], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), [] end. @@ -428,7 +428,7 @@ decode_body(?CONTENT_JSON, Body) -> -spec parse_response({ok, integer(), string()} | {error, any()}) -> {ok, term()} | {error, any()}. parse_response({error, Reason}) -> - ?LOG_DEBUG("HTTP error ~tp", [Reason], #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + ?LOG_DEBUG("HTTP error ~tp", [Reason], #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), {error, lists:flatten(io_lib:format("~tp", [Reason]))}; parse_response({ok, {{_,200,_}, Headers, Body}}) -> {ok, decode_body(proplists:get_value("content-type", Headers, ?CONTENT_JSON), Body)}; @@ -436,7 +436,7 @@ parse_response({ok,{{_,201,_}, Headers, Body}}) -> {ok, decode_body(proplists:get_value("content-type", Headers, ?CONTENT_JSON), Body)}; parse_response({ok,{{_,204,_}, _, _}}) -> {ok, []}; parse_response({ok,{{_Vsn,Code,_Reason},_,Body}}) -> - ?LOG_DEBUG("HTTP Response (~tp) ~ts", [Code, Body], #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + ?LOG_DEBUG("HTTP Response (~tp) ~ts", [Code, Body], #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), {error, integer_to_list(Code)}. %% @private diff --git a/deps/rabbitmq_peer_discovery_common/src/rabbit_peer_discovery_util.erl b/deps/rabbitmq_peer_discovery_common/src/rabbit_peer_discovery_util.erl index 4521a93c2d25..258b0dd3e577 100644 --- a/deps/rabbitmq_peer_discovery_common/src/rabbit_peer_discovery_util.erl +++ b/deps/rabbitmq_peer_discovery_common/src/rabbit_peer_discovery_util.erl @@ -95,7 +95,7 @@ as_atom(Value) -> ?LOG_ERROR( "Unexpected data type for atom value: ~tp", [Value], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), Value. @@ -116,7 +116,7 @@ as_integer(Value) -> ?LOG_ERROR( "Unexpected data type for integer value: ~tp", [Value], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), Value. @@ -140,7 +140,7 @@ as_string(Value) -> ?LOG_ERROR( "Unexpected data type for list value: ~tp", [Value], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), Value. @@ -321,14 +321,14 @@ as_proplist(List) when is_list(List) -> ?LOG_ERROR( "Unexpected data type for proplist value: ~tp. JSON parser returned an error: ~tp!", [Value, Error], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), [] end; as_proplist(Value) -> ?LOG_ERROR( "Unexpected data type for proplist value: ~tp.", [Value], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), []. %%-------------------------------------------------------------------- @@ -352,7 +352,7 @@ as_map(List) when is_list(List) -> ?LOG_ERROR( "Unexpected data type for map value: ~tp. JSON parser returned an error: ~tp!", [Value, Error], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), [] end; as_map(Map) when is_map(Map) -> @@ -361,7 +361,7 @@ as_map(Value) -> ?LOG_ERROR( "Unexpected data type for map value: ~tp.", [Value], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), []. -spec stringify_error({ok, term()} | {error, term()}) -> {ok, term()} | {error, string()}. @@ -387,7 +387,7 @@ maybe_backend_configured(BackendConfigKey, ?LOG_DEBUG( "Peer discovery: translated cluster formation configuration: ~tp", [ClusterFormation], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), case proplists:get_value(BackendConfigKey, ClusterFormation) of undefined -> BackendUndefinedFun(); @@ -395,7 +395,7 @@ maybe_backend_configured(BackendConfigKey, ?LOG_DEBUG( "Peer discovery: cluster formation backend configuration: ~tp", [Proplist], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), ConfiguredFun(Proplist) end end. @@ -428,5 +428,5 @@ as_list(Value) -> ?LOG_ERROR( "Unexpected data type for list value: ~tp", [Value], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), Value. diff --git a/deps/rabbitmq_peer_discovery_consul/src/rabbit_peer_discovery_consul.erl b/deps/rabbitmq_peer_discovery_consul/src/rabbit_peer_discovery_consul.erl index d64af2fc935e..1e55e6549c62 100644 --- a/deps/rabbitmq_peer_discovery_consul/src/rabbit_peer_discovery_consul.erl +++ b/deps/rabbitmq_peer_discovery_consul/src/rabbit_peer_discovery_consul.erl @@ -43,7 +43,7 @@ init() -> ?LOG_DEBUG( "Peer discovery Consul: initialising...", - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), ok = application:ensure_started(inets), %% we cannot start this plugin yet since it depends on the rabbit app, %% which is in the process of being started by the time this function is called @@ -63,7 +63,7 @@ list_nodes() -> "Cannot discover any nodes because Consul cluster " "details are not configured!", [?MODULE], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), {ok, {[], disc}} end, Fun2 = fun(Proplist) -> @@ -112,7 +112,7 @@ register() -> {ok, Body} -> ?LOG_DEBUG( "Consul registration body: ~ts", [Body], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), Path = rabbit_peer_discovery_httpc:build_path([v1, agent, service, register]), Headers = maybe_add_acl([]), HttpOpts = http_options(M), @@ -137,7 +137,7 @@ unregister() -> ID = service_id(), ?LOG_DEBUG( "Unregistering with Consul using service ID '~ts'", [ID], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), Path = rabbit_peer_discovery_httpc:build_path([v1, agent, service, deregister, ID]), Headers = maybe_add_acl([]), HttpOpts = http_options(M), @@ -153,13 +153,13 @@ unregister() -> ?LOG_INFO( "Consul's response to the unregistration attempt: ~tp", [Response], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), ok; Error -> ?LOG_INFO( "Failed to unregister service with ID '~ts` with Consul: ~tp", [ID, Error], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), Error end. @@ -190,7 +190,7 @@ internal_lock() -> M = ?CONFIG_MODULE:config_map(?BACKEND_CONFIG_KEY), ?LOG_DEBUG( "Effective Consul peer discovery configuration: ~tp", [M], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), Node = node(), case create_session(Node, get_config_key(consul_svc_ttl, M)) of {ok, SessionId} -> @@ -209,7 +209,7 @@ internal_unlock({SessionId, TRef}) -> _ = timer:cancel(TRef), ?LOG_DEBUG( "Stopped session renewal", - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), case release_lock(SessionId) of {ok, true} -> ok; @@ -355,7 +355,7 @@ registration_body({error, Reason}) -> ?LOG_ERROR( "Error serializing the request body: ~tp", [Reason], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), {error, Reason}. @@ -403,7 +403,7 @@ registration_body_maybe_add_check(Payload, undefined) -> ?LOG_WARNING( "Can't use Consul's service deregistration feature without " "using TTL. The parameter will be ignored", - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), Payload; _ -> Payload @@ -477,7 +477,7 @@ validate_addr_parameters(false, true) -> "The parameter CONSUL_SVC_ADDR_NODENAME" " can be used only if CONSUL_SVC_ADDR_AUTO is true." " CONSUL_SVC_ADDR_NODENAME value will be ignored.", - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), false; validate_addr_parameters(_, _) -> true. @@ -565,7 +565,7 @@ send_health_check_pass() -> M = ?CONFIG_MODULE:config_map(?BACKEND_CONFIG_KEY), ?LOG_DEBUG( "Running Consul health check", - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), Path = rabbit_peer_discovery_httpc:build_path([v1, agent, check, pass, Service]), Headers = maybe_add_acl([]), HttpOpts = http_options(M), @@ -582,14 +582,14 @@ send_health_check_pass() -> %% Too Many Requests, see https://www.consul.io/docs/agent/checks.html ?LOG_WARNING( "Consul responded to a health check with 429 Too Many Requests", - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), ok; %% starting with Consul 1.11, see https://github.com/hashicorp/consul/pull/11950 {error, "404"} -> ?LOG_WARNING( "Consul responded to a health check with a 404 status, will " "wait and try re-registering", - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), maybe_re_register(wait_for_list_nodes()), ok; %% prior to Consul 1.11, see https://github.com/hashicorp/consul/pull/11950 @@ -597,14 +597,14 @@ send_health_check_pass() -> ?LOG_WARNING( "Consul responded to a health check with a 500 status, will " "wait and try re-registering", - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), maybe_re_register(wait_for_list_nodes()), ok; {error, Reason} -> ?LOG_ERROR( "Error running Consul health check: ~tp", [Reason], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), ok end. @@ -613,7 +613,7 @@ maybe_re_register({error, Reason}) -> "Internal error in Consul while updating health check. " "Cannot obtain list of nodes registered in Consul either: ~tp", [Reason], - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}); + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}); maybe_re_register({ok, {Members, _NodeType}}) -> maybe_re_register(Members); maybe_re_register(Members) -> @@ -621,12 +621,12 @@ maybe_re_register(Members) -> true -> ?LOG_ERROR( "Internal error in Consul while updating health check", - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}); + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}); false -> ?LOG_ERROR( "Internal error in Consul while updating health check, " "node is not registered. Re-registering", - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), register() end. @@ -726,7 +726,7 @@ start_session_ttl_updater(SessionId) -> Interval = get_config_key(consul_svc_ttl, M), ?LOG_DEBUG( "Starting session renewal", - #{domain => ?RMQLOG_DOMAIN_PEER_DIS}), + #{domain => ?RMQLOG_DOMAIN_PEER_DISC}), {ok, TRef} = timer:apply_interval(Interval * 500, ?MODULE, session_ttl_update_callback, [SessionId]), TRef. From 8fb3ca1abf3def8e1f8ed30e0e9bb785ce45d4fe Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Mon, 14 Jul 2025 16:40:34 +0200 Subject: [PATCH 12/31] [skip ci] Set logging domain to `?RMQLOG_DOMAIN_GLOBAL` on startup `?RMQLOG_DOMAIN_GLOBAL` used to be added by a now deleted logging module rabbit_log. --- deps/rabbit/src/rabbit_prelaunch_logging.erl | 2 ++ 1 file changed, 2 insertions(+) diff --git a/deps/rabbit/src/rabbit_prelaunch_logging.erl b/deps/rabbit/src/rabbit_prelaunch_logging.erl index d015583a1ecb..895ca46c39d4 100644 --- a/deps/rabbit/src/rabbit_prelaunch_logging.erl +++ b/deps/rabbit/src/rabbit_prelaunch_logging.erl @@ -501,6 +501,8 @@ clear_config_run_number() -> -spec configure_logger(rabbit_env:context()) -> ok. configure_logger(Context) -> + logger:set_primary_config(metadata, #{domain => ?RMQLOG_DOMAIN_GLOBAL}), + %% Configure main handlers. %% We distinguish them by their type and possibly other %% parameters (file name, syslog settings, etc.). From 301f6e990630af43787e07a19cf3edc60296727f Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Tue, 15 Jul 2025 10:18:50 +0200 Subject: [PATCH 13/31] [skip ci] Remove redundant pid metadata in LOG_ macros --- deps/rabbit/src/rabbit_channel_tracking.erl | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/deps/rabbit/src/rabbit_channel_tracking.erl b/deps/rabbit/src/rabbit_channel_tracking.erl index b3bbbf2e45d5..1c4ede34fe37 100644 --- a/deps/rabbit/src/rabbit_channel_tracking.erl +++ b/deps/rabbit/src/rabbit_channel_tracking.erl @@ -68,13 +68,11 @@ handle_cast({channel_created, Details}) -> error:{no_exists, _} -> Msg = "Could not register channel ~tp for tracking, " "its table is not ready yet or the channel terminated prematurely", - ?LOG_WARNING(Msg, [TrackedChId], #{domain => ?RMQLOG_DOMAIN_CHAN, - pid => self()}), + ?LOG_WARNING(Msg, [TrackedChId], #{domain => ?RMQLOG_DOMAIN_CHAN}), ok; error:Err -> Msg = "Could not register channel ~tp for tracking: ~tp", - ?LOG_WARNING(Msg, [TrackedChId, Err], #{domain => ?RMQLOG_DOMAIN_CHAN, - pid => self()}), + ?LOG_WARNING(Msg, [TrackedChId, Err], #{domain => ?RMQLOG_DOMAIN_CHAN}), ok end; _OtherNode -> @@ -96,7 +94,7 @@ handle_cast({connection_closed, ConnDetails}) -> ?LOG_DEBUG( "Closing ~b channel(s) because connection '~ts' has been closed", [length(TrackedChs), pget(name, ConnDetails)], - #{domain => ?RMQLOG_DOMAIN_CHAN, pid => self()}), + #{domain => ?RMQLOG_DOMAIN_CHAN}), %% Shutting down channels will take care of unregistering the %% corresponding tracking. shutdown_tracked_items(TrackedChs, undefined), From 84d52b51dc4559acc9640da6d671e003b77a9ced Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Tue, 15 Jul 2025 12:28:46 +0200 Subject: [PATCH 14/31] [skip ci] Remove rabbit_log_shovel, use LOG_ macros directly --- .../src/rabbit_amqp10_shovel.erl | 9 +- .../rabbitmq_shovel/src/rabbit_log_shovel.erl | 108 ------------------ .../src/rabbit_shovel_behaviour.erl | 6 +- .../src/rabbit_shovel_dyn_worker_sup.erl | 2 + .../src/rabbit_shovel_dyn_worker_sup_sup.erl | 9 +- .../src/rabbit_shovel_status.erl | 6 +- .../src/rabbit_shovel_util.erl | 2 +- .../src/rabbit_shovel_worker.erl | 55 ++++----- 8 files changed, 52 insertions(+), 145 deletions(-) delete mode 100644 deps/rabbitmq_shovel/src/rabbit_log_shovel.erl diff --git a/deps/rabbitmq_shovel/src/rabbit_amqp10_shovel.erl b/deps/rabbitmq_shovel/src/rabbit_amqp10_shovel.erl index 37e8b1dd34b6..c87751201f88 100644 --- a/deps/rabbitmq_shovel/src/rabbit_amqp10_shovel.erl +++ b/deps/rabbitmq_shovel/src/rabbit_amqp10_shovel.erl @@ -36,7 +36,8 @@ -import(rabbit_misc, [pget/2, pget/3]). -import(rabbit_data_coercion, [to_binary/1]). --define(INFO(Text, Args), rabbit_log_shovel:info(Text, Args)). +-include_lib("kernel/include/logger.hrl"). + -define(LINK_CREDIT_TIMEOUT, 20_000). -type state() :: rabbit_shovel_behaviour:state(). @@ -194,7 +195,7 @@ handle_source({amqp10_event, {connection, Conn, opened}}, handle_source({amqp10_event, {connection, Conn, {closed, Why}}}, #{source := #{current := #{conn := Conn}}, name := Name}) -> - ?INFO("Shovel ~ts source connection closed. Reason: ~tp", [Name, Why]), + ?LOG_INFO("Shovel ~ts source connection closed. Reason: ~tp", [Name, Why]), {stop, {inbound_conn_closed, Why}}; handle_source({amqp10_event, {session, Sess, begun}}, State = #{source := #{current := #{session := Sess}}}) -> @@ -231,7 +232,7 @@ handle_dest({amqp10_disposition, {Result, Tag}}, {#{Tag := IncomingTag}, rejected} -> {1, rabbit_shovel_behaviour:nack(IncomingTag, false, State1)}; _ -> % not found - this should ideally not happen - rabbit_log_shovel:warning("Shovel ~ts amqp10 destination disposition tag not found: ~tp", + ?LOG_WARNING("Shovel ~ts amqp10 destination disposition tag not found: ~tp", [Name, Tag]), {0, State1} end, @@ -242,7 +243,7 @@ handle_dest({amqp10_event, {connection, Conn, opened}}, handle_dest({amqp10_event, {connection, Conn, {closed, Why}}}, #{name := Name, dest := #{current := #{conn := Conn}}}) -> - ?INFO("Shovel ~ts destination connection closed. Reason: ~tp", [Name, Why]), + ?LOG_INFO("Shovel ~ts destination connection closed. Reason: ~tp", [Name, Why]), {stop, {outbound_conn_died, Why}}; handle_dest({amqp10_event, {session, Sess, begun}}, State = #{dest := #{current := #{session := Sess}}}) -> diff --git a/deps/rabbitmq_shovel/src/rabbit_log_shovel.erl b/deps/rabbitmq_shovel/src/rabbit_log_shovel.erl deleted file mode 100644 index 5aa644defc64..000000000000 --- a/deps/rabbitmq_shovel/src/rabbit_log_shovel.erl +++ /dev/null @@ -1,108 +0,0 @@ -%% This Source Code Form is subject to the terms of the Mozilla Public -%% License, v. 2.0. If a copy of the MPL was not distributed with this -%% file, You can obtain one at https://mozilla.org/MPL/2.0/. -%% -%% Copyright (c) 2007-2025 Broadcom. All Rights Reserved. The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. All rights reserved. -%% - -%% @doc Compatibility module for the old Lager-based logging API. --module(rabbit_log_shovel). - --export([debug/1, debug/2, debug/3, - info/1, info/2, info/3, - notice/1, notice/2, notice/3, - warning/1, warning/2, warning/3, - error/1, error/2, error/3, - critical/1, critical/2, critical/3, - alert/1, alert/2, alert/3, - emergency/1, emergency/2, emergency/3, - none/1, none/2, none/3]). - --include("logging.hrl"). --include_lib("kernel/include/logger.hrl"). - --compile({no_auto_import, [error/2, error/3]}). - -%%---------------------------------------------------------------------------- - --spec debug(string()) -> 'ok'. --spec debug(string(), [any()]) -> 'ok'. --spec debug(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec info(string()) -> 'ok'. --spec info(string(), [any()]) -> 'ok'. --spec info(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec notice(string()) -> 'ok'. --spec notice(string(), [any()]) -> 'ok'. --spec notice(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec warning(string()) -> 'ok'. --spec warning(string(), [any()]) -> 'ok'. --spec warning(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec error(string()) -> 'ok'. --spec error(string(), [any()]) -> 'ok'. --spec error(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec critical(string()) -> 'ok'. --spec critical(string(), [any()]) -> 'ok'. --spec critical(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec alert(string()) -> 'ok'. --spec alert(string(), [any()]) -> 'ok'. --spec alert(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec emergency(string()) -> 'ok'. --spec emergency(string(), [any()]) -> 'ok'. --spec emergency(pid() | [tuple()], string(), [any()]) -> 'ok'. --spec none(string()) -> 'ok'. --spec none(string(), [any()]) -> 'ok'. --spec none(pid() | [tuple()], string(), [any()]) -> 'ok'. - -%%---------------------------------------------------------------------------- - -debug(Format) -> debug(Format, []). -debug(Format, Args) -> debug(self(), Format, Args). -debug(Pid, Format, Args) -> - ?LOG_DEBUG(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_SHOVEL}). - -info(Format) -> info(Format, []). -info(Format, Args) -> info(self(), Format, Args). -info(Pid, Format, Args) -> - ?LOG_INFO(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_SHOVEL}). - -notice(Format) -> notice(Format, []). -notice(Format, Args) -> notice(self(), Format, Args). -notice(Pid, Format, Args) -> - ?LOG_NOTICE(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_SHOVEL}). - -warning(Format) -> warning(Format, []). -warning(Format, Args) -> warning(self(), Format, Args). -warning(Pid, Format, Args) -> - ?LOG_WARNING(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_SHOVEL}). - -error(Format) -> error(Format, []). -error(Format, Args) -> error(self(), Format, Args). -error(Pid, Format, Args) -> - ?LOG_ERROR(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_SHOVEL}). - -critical(Format) -> critical(Format, []). -critical(Format, Args) -> critical(self(), Format, Args). -critical(Pid, Format, Args) -> - ?LOG_CRITICAL(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_SHOVEL}). - -alert(Format) -> alert(Format, []). -alert(Format, Args) -> alert(self(), Format, Args). -alert(Pid, Format, Args) -> - ?LOG_ALERT(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_SHOVEL}). - -emergency(Format) -> emergency(Format, []). -emergency(Format, Args) -> emergency(self(), Format, Args). -emergency(Pid, Format, Args) -> - ?LOG_EMERGENCY(Format, Args, #{pid => Pid, - domain => ?RMQLOG_DOMAIN_SHOVEL}). - -none(_Format) -> ok. -none(_Format, _Args) -> ok. -none(_Pid, _Format, _Args) -> ok. diff --git a/deps/rabbitmq_shovel/src/rabbit_shovel_behaviour.erl b/deps/rabbitmq_shovel/src/rabbit_shovel_behaviour.erl index 823dd481e9dc..8f7a890d1698 100644 --- a/deps/rabbitmq_shovel/src/rabbit_shovel_behaviour.erl +++ b/deps/rabbitmq_shovel/src/rabbit_shovel_behaviour.erl @@ -34,6 +34,8 @@ incr_forwarded/1 ]). +-include_lib("kernel/include/logger.hrl"). + -type tag() :: non_neg_integer(). -type uri() :: string() | binary(). -type ack_mode() :: 'no_ack' | 'on_confirm' | 'on_publish'. @@ -189,7 +191,7 @@ decr_remaining(N, State = #{source := #{remaining := M} = Src, case M > N of true -> State#{source => Src#{remaining => M - N}}; false -> - rabbit_log_shovel:info("shutting down Shovel '~ts', no messages left to transfer", [Name]), - rabbit_log_shovel:debug("shutting down Shovel '~ts', no messages left to transfer. Shovel state: ~tp", [Name, State]), + ?LOG_INFO("shutting down Shovel '~ts', no messages left to transfer", [Name]), + ?LOG_DEBUG("shutting down Shovel '~ts', no messages left to transfer. Shovel state: ~tp", [Name, State]), exit({shutdown, autodelete}) end. diff --git a/deps/rabbitmq_shovel/src/rabbit_shovel_dyn_worker_sup.erl b/deps/rabbitmq_shovel/src/rabbit_shovel_dyn_worker_sup.erl index 2ee00b2bcf9a..3155c12af146 100644 --- a/deps/rabbitmq_shovel/src/rabbit_shovel_dyn_worker_sup.erl +++ b/deps/rabbitmq_shovel/src/rabbit_shovel_dyn_worker_sup.erl @@ -15,6 +15,7 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include("rabbit_shovel.hrl"). -include_lib("kernel/include/logger.hrl"). +-include_lib("logging.hrl"). -define(SUPERVISOR, ?MODULE). start_link(Name, Config) -> @@ -35,6 +36,7 @@ maybe_start_link(_, Name, Config) -> %%---------------------------------------------------------------------------- init([Name, Config0]) -> + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_SHOVEL}), Config = rabbit_data_coercion:to_proplist(Config0), Delay = pget(<<"reconnect-delay">>, Config, ?DEFAULT_RECONNECT_DELAY), case Name of diff --git a/deps/rabbitmq_shovel/src/rabbit_shovel_dyn_worker_sup_sup.erl b/deps/rabbitmq_shovel/src/rabbit_shovel_dyn_worker_sup_sup.erl index a3282ba53fb7..2032f6862000 100644 --- a/deps/rabbitmq_shovel/src/rabbit_shovel_dyn_worker_sup_sup.erl +++ b/deps/rabbitmq_shovel/src/rabbit_shovel_dyn_worker_sup_sup.erl @@ -14,6 +14,8 @@ -import(rabbit_misc, [pget/2]). -import(rabbit_data_coercion, [to_map/1, to_list/1]). +-include_lib("kernel/include/logger.hrl"). +-include_lib("logging.hrl"). -include_lib("rabbit_common/include/rabbit.hrl"). -define(SUPERVISOR, ?MODULE). @@ -37,10 +39,10 @@ adjust(Name, Def) -> start_child(Name, Def). start_child({VHost, ShovelName} = Name, Def) -> - rabbit_log_shovel:debug("Asked to start a dynamic Shovel named '~ts' in virtual host '~ts'", [ShovelName, VHost]), + ?LOG_DEBUG("Asked to start a dynamic Shovel named '~ts' in virtual host '~ts'", [ShovelName, VHost]), LockId = rabbit_shovel_locks:lock(Name), cleanup_specs(), - rabbit_log_shovel:debug("Starting a mirrored supervisor named '~ts' in virtual host '~ts'", [ShovelName, VHost]), + ?LOG_DEBUG("Starting a mirrored supervisor named '~ts' in virtual host '~ts'", [ShovelName, VHost]), case child_exists(Name) orelse mirrored_supervisor:start_child( ?SUPERVISOR, @@ -68,7 +70,7 @@ child_exists(Name) -> mirrored_supervisor:which_children(?SUPERVISOR)). stop_child({VHost, ShovelName} = Name) -> - rabbit_log_shovel:debug("Asked to stop a dynamic Shovel named '~ts' in virtual host '~ts'", [ShovelName, VHost]), + ?LOG_DEBUG("Asked to stop a dynamic Shovel named '~ts' in virtual host '~ts'", [ShovelName, VHost]), LockId = rabbit_shovel_locks:lock(Name), case get({shovel_worker_autodelete, Name}) of true -> ok; %% [1] @@ -136,6 +138,7 @@ cleanup_specs() -> %%---------------------------------------------------------------------------- init([]) -> + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_SHOVEL}), {ok, {{one_for_one, 3, 10}, []}}. id({VHost, ShovelName} = Name) diff --git a/deps/rabbitmq_shovel/src/rabbit_shovel_status.erl b/deps/rabbitmq_shovel/src/rabbit_shovel_status.erl index c379b165eadc..f7403bba1f14 100644 --- a/deps/rabbitmq_shovel/src/rabbit_shovel_status.erl +++ b/deps/rabbitmq_shovel/src/rabbit_shovel_status.erl @@ -25,6 +25,9 @@ -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). +-include_lib("kernel/include/logger.hrl"). +-include("logging.hrl"). + -define(SERVER, ?MODULE). -define(ETS_NAME, ?MODULE). -define(CHECK_FREQUENCY, 60000). @@ -113,6 +116,7 @@ get_status_table() -> gen_server:call(?SERVER, get_status_table). init([]) -> + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_SHOVEL}), ?ETS_NAME = ets:new(?ETS_NAME, [named_table, {keypos, #entry.name}, private]), {ok, ensure_timer(#state{})}. @@ -185,7 +189,7 @@ handle_info(check, State) -> rabbit_shovel_dyn_worker_sup_sup:cleanup_specs() catch C:E -> - rabbit_log_shovel:warning("Recurring shovel spec clean up failed with ~p:~p", [C, E]) + ?LOG_WARNING("Recurring shovel spec clean up failed with ~p:~p", [C, E]) end, {noreply, ensure_timer(State)}; handle_info(_Info, State) -> diff --git a/deps/rabbitmq_shovel/src/rabbit_shovel_util.erl b/deps/rabbitmq_shovel/src/rabbit_shovel_util.erl index 2b3cc0ff1ab7..e33ec1058804 100644 --- a/deps/rabbitmq_shovel/src/rabbit_shovel_util.erl +++ b/deps/rabbitmq_shovel/src/rabbit_shovel_util.erl @@ -89,7 +89,7 @@ restart_shovel(VHost, Name) -> not_found -> {error, not_found}; _Obj -> - rabbit_log_shovel:info("Shovel '~ts' in virtual host '~ts' will be restarted", [Name, VHost]), + ?LOG_INFO("Shovel '~ts' in virtual host '~ts' will be restarted", [Name, VHost]), ok = rabbit_shovel_dyn_worker_sup_sup:stop_child({VHost, Name}), {ok, _} = rabbit_shovel_dyn_worker_sup_sup:start_link(), ok diff --git a/deps/rabbitmq_shovel/src/rabbit_shovel_worker.erl b/deps/rabbitmq_shovel/src/rabbit_shovel_worker.erl index 541df58e1334..6ea948dee1d0 100644 --- a/deps/rabbitmq_shovel/src/rabbit_shovel_worker.erl +++ b/deps/rabbitmq_shovel/src/rabbit_shovel_worker.erl @@ -17,6 +17,8 @@ get_internal_config/1]). -include("rabbit_shovel.hrl"). +-include_lib("kernel/include/logger.hrl"). +-include("logging.hrl"). -record(state, {name :: binary() | {rabbit_types:vhost(), binary()}, type :: static | dynamic, @@ -44,6 +46,7 @@ maybe_start_link(_, Type, Name, Config) -> %%--------------------------- init([Type, Name, Config0]) -> + logger:set_process_metadata(#{domain => ?RMQLOG_DOMAIN_SHOVEL}), Config = case Type of static -> Config0; @@ -54,7 +57,7 @@ init([Type, Name, Config0]) -> Config0), Conf end, - rabbit_log_shovel:debug("Initialising a Shovel ~ts of type '~ts'", [human_readable_name(Name), Type]), + ?LOG_DEBUG("Initialising a Shovel ~ts of type '~ts'", [human_readable_name(Name), Type]), gen_server2:cast(self(), init), {ok, #state{name = Name, type = Type, config = Config}}. @@ -62,29 +65,29 @@ handle_call(_Msg, _From, State) -> {noreply, State}. handle_cast(init, State = #state{config = Config0}) -> - rabbit_log_shovel:debug("Shovel ~ts is reporting its status", [human_readable_name(State#state.name)]), + ?LOG_DEBUG("Shovel ~ts is reporting its status", [human_readable_name(State#state.name)]), rabbit_shovel_status:report(State#state.name, State#state.type, starting), - rabbit_log_shovel:info("Shovel ~ts will now try to connect...", [human_readable_name(State#state.name)]), + ?LOG_INFO("Shovel ~ts will now try to connect...", [human_readable_name(State#state.name)]), try rabbit_shovel_behaviour:connect_source(Config0) of Config -> - rabbit_log_shovel:debug("Shovel ~ts connected to source", [human_readable_name(maps:get(name, Config))]), + ?LOG_DEBUG("Shovel ~ts connected to source", [human_readable_name(maps:get(name, Config))]), %% this makes sure that connection pid is updated in case %% any of the subsequent connection/init steps fail. See %% rabbitmq/rabbitmq-shovel#54 for context. gen_server2:cast(self(), connect_dest), {noreply, State#state{config = Config}} catch E:R -> - rabbit_log_shovel:error("Shovel ~ts could not connect to source: ~p ~p", [human_readable_name(maps:get(name, Config0)), E, R]), + ?LOG_ERROR("Shovel ~ts could not connect to source: ~p ~p", [human_readable_name(maps:get(name, Config0)), E, R]), {stop, shutdown, State} end; handle_cast(connect_dest, State = #state{config = Config0}) -> try rabbit_shovel_behaviour:connect_dest(Config0) of Config -> - rabbit_log_shovel:debug("Shovel ~ts connected to destination", [human_readable_name(maps:get(name, Config))]), + ?LOG_DEBUG("Shovel ~ts connected to destination", [human_readable_name(maps:get(name, Config))]), gen_server2:cast(self(), init_shovel), {noreply, State#state{config = Config}} catch E:R -> - rabbit_log_shovel:error("Shovel ~ts could not connect to destination: ~p ~p", [human_readable_name(maps:get(name, Config0)), E, R]), + ?LOG_ERROR("Shovel ~ts could not connect to destination: ~p ~p", [human_readable_name(maps:get(name, Config0)), E, R]), {stop, shutdown, State} end; handle_cast(init_shovel, State = #state{config = Config}) -> @@ -94,7 +97,7 @@ handle_cast(init_shovel, State = #state{config = Config}) -> process_flag(trap_exit, true), Config1 = rabbit_shovel_behaviour:init_dest(Config), Config2 = rabbit_shovel_behaviour:init_source(Config1), - rabbit_log_shovel:debug("Shovel ~ts has finished setting up its topology", [human_readable_name(maps:get(name, Config2))]), + ?LOG_DEBUG("Shovel ~ts has finished setting up its topology", [human_readable_name(maps:get(name, Config2))]), State1 = State#state{config = Config2}, ok = report_running(State1), {noreply, State1}. @@ -105,19 +108,19 @@ handle_info(Msg, State = #state{config = Config, name = Name}) -> not_handled -> case rabbit_shovel_behaviour:handle_dest(Msg, Config) of not_handled -> - rabbit_log_shovel:warning("Shovel ~ts could not handle a destination message ~tp", [human_readable_name(Name), Msg]), + ?LOG_WARNING("Shovel ~ts could not handle a destination message ~tp", [human_readable_name(Name), Msg]), {noreply, State}; {stop, {outbound_conn_died, heartbeat_timeout}} -> - rabbit_log_shovel:error("Shovel ~ts detected missed heartbeats on destination connection", [human_readable_name(Name)]), + ?LOG_ERROR("Shovel ~ts detected missed heartbeats on destination connection", [human_readable_name(Name)]), {stop, {shutdown, heartbeat_timeout}, State}; {stop, {outbound_conn_died, Reason}} -> - rabbit_log_shovel:error("Shovel ~ts detected destination connection failure: ~tp", [human_readable_name(Name), Reason]), + ?LOG_ERROR("Shovel ~ts detected destination connection failure: ~tp", [human_readable_name(Name), Reason]), {stop, Reason, State}; {stop, {outbound_link_or_channel_closure, Reason}} -> - rabbit_log_shovel:error("Shovel ~ts detected destination shovel failure: ~tp", [human_readable_name(Name), Reason]), + ?LOG_ERROR("Shovel ~ts detected destination shovel failure: ~tp", [human_readable_name(Name), Reason]), {stop, Reason, State}; {stop, Reason} -> - rabbit_log_shovel:debug("Shovel ~ts decided to stop due a message from destination: ~tp", [human_readable_name(Name), Reason]), + ?LOG_DEBUG("Shovel ~ts decided to stop due a message from destination: ~tp", [human_readable_name(Name), Reason]), {stop, Reason, State}; Config1 -> State1 = State#state{config = Config1}, @@ -125,16 +128,16 @@ handle_info(Msg, State = #state{config = Config, name = Name}) -> {noreply, State2} end; {stop, {inbound_conn_died, heartbeat_timeout}} -> - rabbit_log_shovel:error("Shovel ~ts detected missed heartbeats on source connection", [human_readable_name(Name)]), + ?LOG_ERROR("Shovel ~ts detected missed heartbeats on source connection", [human_readable_name(Name)]), {stop, {shutdown, heartbeat_timeout}, State}; {stop, {inbound_conn_died, Reason}} -> - rabbit_log_shovel:error("Shovel ~ts detected source connection failure: ~tp", [human_readable_name(Name), Reason]), + ?LOG_ERROR("Shovel ~ts detected source connection failure: ~tp", [human_readable_name(Name), Reason]), {stop, Reason, State}; {stop, {inbound_link_or_channel_closure, Reason}} -> - rabbit_log_shovel:error("Shovel ~ts detected source Shovel (or link, or channel) failure: ~tp", [human_readable_name(Name), Reason]), + ?LOG_ERROR("Shovel ~ts detected source Shovel (or link, or channel) failure: ~tp", [human_readable_name(Name), Reason]), {stop, Reason, State}; {stop, Reason} -> - rabbit_log_shovel:error("Shovel ~ts decided to stop due a message from source: ~tp", [human_readable_name(Name), Reason]), + ?LOG_ERROR("Shovel ~ts decided to stop due a message from source: ~tp", [human_readable_name(Name), Reason]), {stop, Reason, State}; Config1 -> State1 = State#state{config = Config1}, @@ -145,7 +148,7 @@ handle_info(Msg, State = #state{config = Config, name = Name}) -> terminate({shutdown, autodelete}, State = #state{name = Name, type = dynamic}) -> {VHost, ShovelName} = Name, - rabbit_log_shovel:info("Shovel '~ts' is stopping (it was configured to autodelete and transfer is completed)", + ?LOG_INFO("Shovel '~ts' is stopping (it was configured to autodelete and transfer is completed)", [human_readable_name(Name)]), close_connections(State), %% See rabbit_shovel_dyn_worker_sup_sup:stop_child/1 @@ -158,43 +161,43 @@ terminate(shutdown, State = #state{name = Name}) -> rabbit_shovel_status:remove(Name), ok; terminate(socket_closed_unexpectedly, State = #state{name = Name}) -> - rabbit_log_shovel:error("Shovel ~ts is stopping because of the socket closed unexpectedly", [human_readable_name(Name)]), + ?LOG_ERROR("Shovel ~ts is stopping because of the socket closed unexpectedly", [human_readable_name(Name)]), rabbit_shovel_status:report(State#state.name, State#state.type, {terminated, "socket closed"}), close_connections(State), ok; terminate({'EXIT', heartbeat_timeout}, State = #state{name = Name}) -> - rabbit_log_shovel:error("Shovel ~ts is stopping because of a heartbeat timeout", [human_readable_name(Name)]), + ?LOG_ERROR("Shovel ~ts is stopping because of a heartbeat timeout", [human_readable_name(Name)]), rabbit_shovel_status:report(State#state.name, State#state.type, {terminated, "heartbeat timeout"}), close_connections(State), ok; terminate({'EXIT', outbound_conn_died}, State = #state{name = Name}) -> - rabbit_log_shovel:error("Shovel ~ts is stopping because destination connection failed", [human_readable_name(Name)]), + ?LOG_ERROR("Shovel ~ts is stopping because destination connection failed", [human_readable_name(Name)]), rabbit_shovel_status:report(State#state.name, State#state.type, {terminated, "destination connection failed"}), close_connections(State), ok; terminate({'EXIT', inbound_conn_died}, State = #state{name = Name}) -> - rabbit_log_shovel:error("Shovel ~ts is stopping because destination connection failed", [human_readable_name(Name)]), + ?LOG_ERROR("Shovel ~ts is stopping because destination connection failed", [human_readable_name(Name)]), rabbit_shovel_status:report(State#state.name, State#state.type, {terminated, "source connection failed"}), close_connections(State), ok; terminate({shutdown, heartbeat_timeout}, State = #state{name = Name}) -> - rabbit_log_shovel:error("Shovel ~ts is stopping because of a heartbeat timeout", [human_readable_name(Name)]), + ?LOG_ERROR("Shovel ~ts is stopping because of a heartbeat timeout", [human_readable_name(Name)]), rabbit_shovel_status:report(State#state.name, State#state.type, {terminated, "heartbeat timeout"}), close_connections(State), ok; terminate({shutdown, restart}, State = #state{name = Name}) -> - rabbit_log_shovel:error("Shovel ~ts is stopping to restart", [human_readable_name(Name)]), + ?LOG_ERROR("Shovel ~ts is stopping to restart", [human_readable_name(Name)]), rabbit_shovel_status:report(State#state.name, State#state.type, {terminated, "needed a restart"}), close_connections(State), ok; terminate({{shutdown, {server_initiated_close, Code, Reason}}, _}, State = #state{name = Name}) -> - rabbit_log_shovel:error("Shovel ~ts is stopping: one of its connections closed " + ?LOG_ERROR("Shovel ~ts is stopping: one of its connections closed " "with code ~b, reason: ~ts", [human_readable_name(Name), Code, Reason]), rabbit_shovel_status:report(State#state.name, State#state.type, @@ -202,7 +205,7 @@ terminate({{shutdown, {server_initiated_close, Code, Reason}}, _}, State = #stat close_connections(State), ok; terminate(Reason, State = #state{name = Name}) -> - rabbit_log_shovel:error("Shovel ~ts is stopping, reason: ~tp", [human_readable_name(Name), Reason]), + ?LOG_ERROR("Shovel ~ts is stopping, reason: ~tp", [human_readable_name(Name), Reason]), rabbit_shovel_status:report(State#state.name, State#state.type, {terminated, Reason}), close_connections(State), From 24c3677e92650beb13275aa9372191c234f3c5f5 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Tue, 15 Jul 2025 12:46:29 +0200 Subject: [PATCH 15/31] [skip ci] fix AMQP-1.0 DBG macro --- deps/amqp10_client/src/amqp10_client_internal.hrl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deps/amqp10_client/src/amqp10_client_internal.hrl b/deps/amqp10_client/src/amqp10_client_internal.hrl index a549c47339ea..1a3929004803 100644 --- a/deps/amqp10_client/src/amqp10_client_internal.hrl +++ b/deps/amqp10_client/src/amqp10_client_internal.hrl @@ -12,7 +12,7 @@ % -define(debug, true). -ifdef(debug). --define(DBG(F, A), error_?LOG_INFO_msg(F, A)). +-define(DBG(F, A), ?LOG_INFO(F, A)). -else. -define(DBG(F, A), ok). -endif. From 0cfab72feae567eda93eb40c5d8d43e3ba773202 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Tue, 15 Jul 2025 13:22:14 +0200 Subject: [PATCH 16/31] Fix AMQP-0.8 :) --- deps/rabbit_common/codegen.py | 1 + 1 file changed, 1 insertion(+) diff --git a/deps/rabbit_common/codegen.py b/deps/rabbit_common/codegen.py index ce752fbd95d7..d44365e95921 100755 --- a/deps/rabbit_common/codegen.py +++ b/deps/rabbit_common/codegen.py @@ -311,6 +311,7 @@ def genAmqpException(c,v,cls): module = "rabbit_framing_amqp_0_8" print("-module(%s)." % module) print("""-include("rabbit_framing.hrl"). +-include_lib("kernel/include/logger.hrl"). -export([version/0]). -export([lookup_method_name/1]). From 34d20d92ed93819782196b899deac787bdeb3de8 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Tue, 15 Jul 2025 14:13:53 +0200 Subject: [PATCH 17/31] Remove incorrect include --- .../src/rabbit_federation_queue_link_sup_sup.erl | 1 - 1 file changed, 1 deletion(-) diff --git a/deps/rabbitmq_queue_federation/src/rabbit_federation_queue_link_sup_sup.erl b/deps/rabbitmq_queue_federation/src/rabbit_federation_queue_link_sup_sup.erl index 29d2ee88d15b..a0b6ebb78fd9 100644 --- a/deps/rabbitmq_queue_federation/src/rabbit_federation_queue_link_sup_sup.erl +++ b/deps/rabbitmq_queue_federation/src/rabbit_federation_queue_link_sup_sup.erl @@ -13,7 +13,6 @@ -include_lib("rabbit/include/amqqueue.hrl"). -include("rabbit_queue_federation.hrl"). -include_lib("kernel/include/logger.hrl"). --include("rabbit_federation.hrl"). -define(SUPERVISOR, ?MODULE). %% Supervises the upstream links for all queues (but not exchanges). We need From cc5c3c60df54611ee3db76525d30a5d0e793ebd3 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Tue, 15 Jul 2025 14:25:06 +0200 Subject: [PATCH 18/31] Add missing include --- .../src/rabbit_queue_federation_app.erl | 1 + 1 file changed, 1 insertion(+) diff --git a/deps/rabbitmq_queue_federation/src/rabbit_queue_federation_app.erl b/deps/rabbitmq_queue_federation/src/rabbit_queue_federation_app.erl index 60c75eae69f3..41519d1ac794 100644 --- a/deps/rabbitmq_queue_federation/src/rabbit_queue_federation_app.erl +++ b/deps/rabbitmq_queue_federation/src/rabbit_queue_federation_app.erl @@ -8,6 +8,7 @@ -module(rabbit_queue_federation_app). -include_lib("rabbitmq_federation_common/include/rabbit_federation.hrl"). +-include_lib("rabbitmq_federation_common/include/logging.hrl"). -include("rabbit_queue_federation.hrl"). -behaviour(application). From 8ffc9912cdf15d7f5e29f78ae448ebf6b73b17f4 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Tue, 15 Jul 2025 14:31:09 +0200 Subject: [PATCH 19/31] Add missing includes --- .../src/rabbit_exchange_federation_app.erl | 1 + .../src/rabbit_federation_exchange_link.erl | 1 + .../src/rabbit_federation_exchange_link_sup_sup.erl | 3 ++- 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/deps/rabbitmq_exchange_federation/src/rabbit_exchange_federation_app.erl b/deps/rabbitmq_exchange_federation/src/rabbit_exchange_federation_app.erl index 28b79a27a2e3..48ba631a02c3 100644 --- a/deps/rabbitmq_exchange_federation/src/rabbit_exchange_federation_app.erl +++ b/deps/rabbitmq_exchange_federation/src/rabbit_exchange_federation_app.erl @@ -8,6 +8,7 @@ -module(rabbit_exchange_federation_app). -include_lib("rabbitmq_federation_common/include/rabbit_federation.hrl"). +-include_lib("rabbitmq_federation_common/include/logging.hrl"). -include("rabbit_exchange_federation.hrl"). -include_lib("kernel/include/logger.hrl"). diff --git a/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link.erl b/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link.erl index 997e9e21e3a4..9038acd93104 100644 --- a/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link.erl +++ b/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link.erl @@ -9,6 +9,7 @@ -include_lib("amqp_client/include/amqp_client.hrl"). -include_lib("rabbitmq_federation_common/include/rabbit_federation.hrl"). +-include_lib("rabbitmq_federation_common/include/logging.hrl"). -include("rabbit_exchange_federation.hrl"). -include_lib("kernel/include/logger.hrl"). diff --git a/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link_sup_sup.erl b/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link_sup_sup.erl index 8b36e4b6d916..9b5b80220b0a 100644 --- a/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link_sup_sup.erl +++ b/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link_sup_sup.erl @@ -12,7 +12,8 @@ -include_lib("rabbit_common/include/rabbit.hrl"). -include("rabbit_exchange_federation.hrl"). -include_lib("kernel/include/logger.hrl"). --include_lib("rabbit_federation.hrl"). +-include_lib("rabbitmq_federation_common/include/logging.hrl"). + -define(SUPERVISOR, ?MODULE). %% Supervises the upstream links for all exchanges (but not queues). We need From d9103c9d6ecd421024e7cb05e89d0279155c3830 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Tue, 15 Jul 2025 14:55:13 +0200 Subject: [PATCH 20/31] Add exchange name back to the log --- .../src/rabbit_federation_exchange_link.erl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link.erl b/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link.erl index 9038acd93104..b9a94ebba088 100644 --- a/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link.erl +++ b/deps/rabbitmq_exchange_federation/src/rabbit_federation_exchange_link.erl @@ -630,12 +630,12 @@ check_internal_exchange(IntXNameBin, arguments = XFUArgs}, rabbit_federation_link_util:disposable_connection_call( Params, XFU, fun(404, Text) -> - ?LOG_WARNING("detected internal upstream exchange changes," - " restarting link: ~tp", [Text]), + ?LOG_WARNING("Federation ~ts detected internal upstream exchange changes," + " restarting link: ~tp", [rabbit_misc:rs(XName), Text]), upstream_not_found; (Code, Text) -> - ?LOG_WARNING("internal upstream exchange check failed: ~tp ~tp", - [Code, Text]), + ?LOG_WARNING("Federation ~ts internal upstream exchange check failed: ~tp ~tp", + [rabbit_misc:rs(XName), Code, Text]), error end). From 11e51f58ac6de2efe429a988826e131b716168b6 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Tue, 15 Jul 2025 14:55:03 +0200 Subject: [PATCH 21/31] Make dialyzer happy --- deps/rabbit/src/rabbit_boot_steps.erl | 2 +- deps/rabbit/src/rabbit_classic_queue.erl | 2 +- deps/rabbit/src/rabbit_prelaunch_logging.erl | 2 +- deps/rabbit/src/rabbit_quorum_queue.erl | 4 ++-- deps/rabbit/src/rabbit_vhosts.erl | 2 +- .../src/rabbit_exchange_type_consistent_hash.erl | 4 ++-- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/deps/rabbit/src/rabbit_boot_steps.erl b/deps/rabbit/src/rabbit_boot_steps.erl index f62da5e6097a..5dc61cdd8090 100644 --- a/deps/rabbit/src/rabbit_boot_steps.erl +++ b/deps/rabbit/src/rabbit_boot_steps.erl @@ -47,7 +47,7 @@ find_steps(Apps) -> [Step || {App, _, _} = Step <- All, lists:member(App, Apps)]. run_step(Attributes, AttributeName) -> - [begin + _ = [begin ?LOG_DEBUG("Applying MFA: M = ~ts, F = ~ts, A = ~tp", [M, F, A]), case apply(M,F,A) of diff --git a/deps/rabbit/src/rabbit_classic_queue.erl b/deps/rabbit/src/rabbit_classic_queue.erl index a00bea79d466..125a95173a0f 100644 --- a/deps/rabbit/src/rabbit_classic_queue.erl +++ b/deps/rabbit/src/rabbit_classic_queue.erl @@ -589,7 +589,7 @@ recover_durable_queues(QueuesAndRecoveryTerms) -> gen_server2:mcall( [{rabbit_amqqueue_sup_sup:start_queue_process(node(), Q), {init, {self(), Terms}}} || {Q, Terms} <- QueuesAndRecoveryTerms]), - [?LOG_ERROR("Queue ~tp failed to initialise: ~tp", + _ = [?LOG_ERROR("Queue ~tp failed to initialise: ~tp", [Pid, Error]) || {Pid, Error} <- Failures], [Q || {_, {new, Q}} <- Results]. diff --git a/deps/rabbit/src/rabbit_prelaunch_logging.erl b/deps/rabbit/src/rabbit_prelaunch_logging.erl index 895ca46c39d4..61db67459ba3 100644 --- a/deps/rabbit/src/rabbit_prelaunch_logging.erl +++ b/deps/rabbit/src/rabbit_prelaunch_logging.erl @@ -501,7 +501,7 @@ clear_config_run_number() -> -spec configure_logger(rabbit_env:context()) -> ok. configure_logger(Context) -> - logger:set_primary_config(metadata, #{domain => ?RMQLOG_DOMAIN_GLOBAL}), + _ = logger:set_primary_config(metadata, #{domain => ?RMQLOG_DOMAIN_GLOBAL}), %% Configure main handlers. %% We distinguish them by their type and possibly other diff --git a/deps/rabbit/src/rabbit_quorum_queue.erl b/deps/rabbit/src/rabbit_quorum_queue.erl index 5cf33fbde0db..5ae9a8a73973 100644 --- a/deps/rabbit/src/rabbit_quorum_queue.erl +++ b/deps/rabbit/src/rabbit_quorum_queue.erl @@ -2303,7 +2303,7 @@ transfer_leadership(_TransferCandidates) -> Queues = rabbit_amqqueue:list_local_leaders(), ?LOG_INFO("Will transfer leadership of ~b quorum queues with current leader on this node", [length(Queues)]), - [begin + _ = [begin Name = amqqueue:get_name(Q), ?LOG_DEBUG("Will trigger a leader election for local quorum queue ~ts", [rabbit_misc:rs(Name)]), @@ -2326,7 +2326,7 @@ stop_local_quorum_queue_followers() -> Queues = rabbit_amqqueue:list_local_followers(), ?LOG_INFO("Will stop local follower replicas of ~b quorum queues on this node", [length(Queues)]), - [begin + _ = [begin Name = amqqueue:get_name(Q), ?LOG_DEBUG("Will stop a local follower replica of quorum queue ~ts", [rabbit_misc:rs(Name)]), diff --git a/deps/rabbit/src/rabbit_vhosts.erl b/deps/rabbit/src/rabbit_vhosts.erl index e8bac94cb581..7bc44f4135d6 100644 --- a/deps/rabbit/src/rabbit_vhosts.erl +++ b/deps/rabbit/src/rabbit_vhosts.erl @@ -115,7 +115,7 @@ start_processes_for_all(Nodes) -> Names = list_names(), N = length(Names), ?LOG_DEBUG("Will make sure that processes of ~p virtual hosts are running on all reachable cluster nodes", [N]), - [begin + _ = [begin try start_on_all_nodes(VH, Nodes) catch diff --git a/deps/rabbitmq_consistent_hash_exchange/src/rabbit_exchange_type_consistent_hash.erl b/deps/rabbitmq_consistent_hash_exchange/src/rabbit_exchange_type_consistent_hash.erl index e5a4f755f4f7..23a079eaf360 100644 --- a/deps/rabbitmq_consistent_hash_exchange/src/rabbit_exchange_type_consistent_hash.erl +++ b/deps/rabbitmq_consistent_hash_exchange/src/rabbit_exchange_type_consistent_hash.erl @@ -143,7 +143,7 @@ recover_exchange_and_bindings(#exchange{name = XName} = X) -> Bindings = rabbit_binding:list_for_source(XName), ?LOG_DEBUG("Consistent hashing exchange: have ~b bindings to recover for exchange ~ts", [length(Bindings), rabbit_misc:rs(XName)]), - [add_binding(none, X, B) || B <- lists:usort(Bindings)], + _ = [add_binding(none, X, B) || B <- lists:usort(Bindings)], ?LOG_DEBUG("Consistent hashing exchange: recovered bindings for exchange ~ts", [rabbit_misc:rs(XName)]). @@ -191,7 +191,7 @@ chx_hash_ring_update_fun(#chx_hash_ring{bucket_map = BM0, remove_bindings(_Serial, _X, Bindings) -> Ret = rabbit_db_ch_exchange:delete_bindings(Bindings, fun ch_hash_ring_delete_fun/2), - [?LOG_WARNING("Can't remove binding: hash ring state for exchange ~s wasn't found", + _ = [?LOG_WARNING("Can't remove binding: hash ring state for exchange ~s wasn't found", [rabbit_misc:rs(X)]) || {not_found, X} <- Ret], ok. From 5cfb39d30b6f017f9b79c158bf1be8c3b2c526d8 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Tue, 15 Jul 2025 20:50:54 +0200 Subject: [PATCH 22/31] rabbit_log -> logger in dynamic calls --- deps/rabbit/src/rabbit_fifo_dlx.erl | 4 ++-- deps/rabbit/test/rabbit_fifo_dlx_SUITE.erl | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/deps/rabbit/src/rabbit_fifo_dlx.erl b/deps/rabbit/src/rabbit_fifo_dlx.erl index cb87da2ea0f3..53f404bb85cf 100644 --- a/deps/rabbit/src/rabbit_fifo_dlx.erl +++ b/deps/rabbit/src/rabbit_fifo_dlx.erl @@ -316,7 +316,7 @@ update_config(at_least_once, at_least_once, _, State) -> update_config(SameDLH, SameDLH, _, State) -> {State, []}; update_config(OldDLH, NewDLH, QRes, State0) -> - LogOnLeader = {mod_call, rabbit_log, debug, + LogOnLeader = {mod_call, logger, debug, ["Switching dead_letter_handler from ~tp to ~tp for ~ts", [OldDLH, NewDLH, rabbit_misc:rs(QRes)]]}, {State1, Effects0} = switch_from(OldDLH, QRes, State0), @@ -330,7 +330,7 @@ switch_from(at_least_once, QRes, State) -> ensure_worker_terminated(State), {Num, Bytes} = stat(State), %% Log only on leader. - {init(), [{mod_call, rabbit_log, info, + {init(), [{mod_call, logger, info, ["Deleted ~b dead-lettered messages (with total messages size of ~b bytes) in ~ts", [Num, Bytes, rabbit_misc:rs(QRes)]]}]}; switch_from(_, _, State) -> diff --git a/deps/rabbit/test/rabbit_fifo_dlx_SUITE.erl b/deps/rabbit/test/rabbit_fifo_dlx_SUITE.erl index a898458290a5..03dbb90d76dc 100644 --- a/deps/rabbit/test/rabbit_fifo_dlx_SUITE.erl +++ b/deps/rabbit/test/rabbit_fifo_dlx_SUITE.erl @@ -135,7 +135,7 @@ switch_strategies(_Config) -> Handler1 = at_least_once, %% Switching from undefined to at_least_once should start dlx consumer. {S1, Effects0} = rabbit_fifo_dlx:update_config(Handler0, Handler1, QRes, S0), - ?assertEqual([{mod_call, rabbit_log, debug, + ?assertEqual([{mod_call, logger, debug, ["Switching dead_letter_handler from ~tp to ~tp for ~ts", [undefined, at_least_once, "queue 'blah' in vhost '/'"]]}, {aux, {dlx, setup}}], @@ -150,10 +150,10 @@ switch_strategies(_Config) -> %% Switching from at_least_once to undefined should terminate dlx consumer. {S5, Effects} = rabbit_fifo_dlx:update_config(Handler1, Handler0, QRes, S4), - ?assertEqual([{mod_call, rabbit_log, debug, + ?assertEqual([{mod_call, logger, debug, ["Switching dead_letter_handler from ~tp to ~tp for ~ts", [at_least_once, undefined, "queue 'blah' in vhost '/'"]]}, - {mod_call, rabbit_log, info, + {mod_call, logger, info, ["Deleted ~b dead-lettered messages (with total messages size of ~b bytes) in ~ts", [1, 1, "queue 'blah' in vhost '/'"]]}], Effects), From 4a4b8bea60ada67498595dc5265543347418c8eb Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Tue, 15 Jul 2025 20:58:06 +0200 Subject: [PATCH 23/31] Don't meck rabbit_log --- .../test/rabbitmq_peer_discovery_consul_SUITE.erl | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/deps/rabbitmq_peer_discovery_consul/test/rabbitmq_peer_discovery_consul_SUITE.erl b/deps/rabbitmq_peer_discovery_consul/test/rabbitmq_peer_discovery_consul_SUITE.erl index a0734b265875..e73687ccdd0f 100644 --- a/deps/rabbitmq_peer_discovery_consul/test/rabbitmq_peer_discovery_consul_SUITE.erl +++ b/deps/rabbitmq_peer_discovery_consul/test/rabbitmq_peer_discovery_consul_SUITE.erl @@ -131,7 +131,6 @@ reset() -> init_per_testcase(_TC, Config) -> reset(), - meck:new(rabbit_log, []), meck:new(rabbit_peer_discovery_httpc, [passthrough]), meck:new(rabbit_nodes, [passthrough]), Config. @@ -508,7 +507,6 @@ list_nodes_return_value_nodes_in_warning_state_filtered_out_test(_Config) -> ?assert(meck:validate(rabbit_peer_discovery_httpc)). registration_with_all_default_values_test(_Config) -> - meck:expect(rabbit_log, debug, fun(_Message) -> ok end), meck:expect(rabbit_peer_discovery_httpc, put, fun(Scheme, Host, Port, Path, Args, Headers, _HttpOpts, Body) -> ?assertEqual("http", Scheme), @@ -523,7 +521,6 @@ registration_with_all_default_values_test(_Config) -> {ok, []} end), ?assertEqual(ok, rabbit_peer_discovery_consul:register()), - ?assert(meck:validate(rabbit_log)), ?assert(meck:validate(rabbit_peer_discovery_httpc)). registration_with_cluster_name_test(_Config) -> @@ -760,16 +757,12 @@ health_check_with_acl_token_test(_Config) -> ?assert(meck:validate(rabbit_peer_discovery_httpc)). health_check_error_handling_test(_Config) -> - meck:expect(rabbit_log, error, fun(_Message, _Args) -> - ok - end), meck:expect(rabbit_peer_discovery_httpc, put, fun(_Scheme, _Host, _Port, _Path, _Args, _Headers, _HttpOpts, _Body) -> {error, "testing"} end), ?assertEqual(ok, rabbit_peer_discovery_consul:send_health_check_pass()), - ?assert(meck:validate(rabbit_peer_discovery_httpc)), - ?assert(meck:validate(rabbit_log)). + ?assert(meck:validate(rabbit_peer_discovery_httpc)). unregistration_with_all_defaults_test(_Config) -> From 9ab45124e6896be58b68463bfd7566c502b9c4c4 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Tue, 15 Jul 2025 20:58:30 +0200 Subject: [PATCH 24/31] rabbit_log -> logger in CLI tests --- deps/rabbitmq_cli/mix.exs | 1 - .../test/diagnostics/log_location_command_test.exs | 6 +++--- .../test/diagnostics/log_tail_command_test.exs | 6 +++--- .../test/diagnostics/log_tail_stream_command_test.exs | 10 +++++----- 4 files changed, 11 insertions(+), 12 deletions(-) diff --git a/deps/rabbitmq_cli/mix.exs b/deps/rabbitmq_cli/mix.exs index 9128880ae88e..b18794477907 100644 --- a/deps/rabbitmq_cli/mix.exs +++ b/deps/rabbitmq_cli/mix.exs @@ -39,7 +39,6 @@ defmodule RabbitMQCtl.MixfileBase do :rabbit_event, :rabbit_file, :rabbit_net, - :rabbit_log, :rabbit_misc, :rabbit_mnesia, :rabbit_nodes_common, diff --git a/deps/rabbitmq_cli/test/diagnostics/log_location_command_test.exs b/deps/rabbitmq_cli/test/diagnostics/log_location_command_test.exs index 2ac7031669b1..4be8a9169629 100644 --- a/deps/rabbitmq_cli/test/diagnostics/log_location_command_test.exs +++ b/deps/rabbitmq_cli/test/diagnostics/log_location_command_test.exs @@ -56,7 +56,7 @@ defmodule LogLocationCommandTest do test "run: prints default log location", context do {:ok, logfile} = @command.run([], context[:opts]) log_message = "file location" - :rpc.call(get_rabbit_hostname(), :rabbit_log, :error, [to_charlist(log_message)]) + :rpc.call(get_rabbit_hostname(), :logger, :error, [to_charlist(log_message)]) wait_for_log_message(log_message, logfile) {:ok, log_file_data} = File.read(logfile) assert String.match?(log_file_data, Regex.compile!(log_message)) @@ -67,12 +67,12 @@ defmodule LogLocationCommandTest do [logfile | _] = @command.run([], Map.merge(context[:opts], %{all: true})) log_message = "checking the default log file when checking all" - :rpc.call(get_rabbit_hostname(), :rabbit_log, :error, [to_charlist(log_message)]) + :rpc.call(get_rabbit_hostname(), :logger, :error, [to_charlist(log_message)]) wait_for_log_message(log_message, logfile) log_message_upgrade = "checking the upgrade log file when checking all" - :rpc.call(get_rabbit_hostname(), :rabbit_log, :log, [ + :rpc.call(get_rabbit_hostname(), :logger, :log, [ :upgrade, :error, to_charlist(log_message_upgrade), diff --git a/deps/rabbitmq_cli/test/diagnostics/log_tail_command_test.exs b/deps/rabbitmq_cli/test/diagnostics/log_tail_command_test.exs index 3a58b2a74dfd..75539c6cbcd2 100644 --- a/deps/rabbitmq_cli/test/diagnostics/log_tail_command_test.exs +++ b/deps/rabbitmq_cli/test/diagnostics/log_tail_command_test.exs @@ -61,7 +61,7 @@ defmodule LogTailCommandTest do :lists.seq(1, 50), fn n -> message = "Getting log tail #{n}" - :rpc.call(get_rabbit_hostname(), :rabbit_log, :error, [to_charlist(message)]) + :rpc.call(get_rabbit_hostname(), :logger, :error, [to_charlist(message)]) message end ) @@ -84,7 +84,7 @@ defmodule LogTailCommandTest do :lists.seq(1, 50), fn n -> message = "More lines #{n}" - :rpc.call(get_rabbit_hostname(), :rabbit_log, :error, [to_charlist(message)]) + :rpc.call(get_rabbit_hostname(), :logger, :error, [to_charlist(message)]) message end ) @@ -102,7 +102,7 @@ defmodule LogTailCommandTest do :lists.seq(1, 100), fn n -> message = "More lines #{n}" - :rpc.call(get_rabbit_hostname(), :rabbit_log, :error, [to_charlist(message)]) + :rpc.call(get_rabbit_hostname(), :logger, :error, [to_charlist(message)]) message end ) diff --git a/deps/rabbitmq_cli/test/diagnostics/log_tail_stream_command_test.exs b/deps/rabbitmq_cli/test/diagnostics/log_tail_stream_command_test.exs index d5d468a47631..72c8011360ec 100644 --- a/deps/rabbitmq_cli/test/diagnostics/log_tail_stream_command_test.exs +++ b/deps/rabbitmq_cli/test/diagnostics/log_tail_stream_command_test.exs @@ -58,10 +58,10 @@ defmodule LogTailStreamCommandTest do time_before = System.system_time(:second) stream = @command.run([], Map.merge(context[:opts], %{duration: 15})) - :rpc.call(get_rabbit_hostname(), :rabbit_log, :error, [to_charlist("Message")]) - :rpc.call(get_rabbit_hostname(), :rabbit_log, :error, [to_charlist("Message1")]) - :rpc.call(get_rabbit_hostname(), :rabbit_log, :error, [to_charlist("Message2")]) - :rpc.call(get_rabbit_hostname(), :rabbit_log, :error, [to_charlist("Message3")]) + :rpc.call(get_rabbit_hostname(), :logger, :error, [to_charlist("Message")]) + :rpc.call(get_rabbit_hostname(), :logger, :error, [to_charlist("Message1")]) + :rpc.call(get_rabbit_hostname(), :logger, :error, [to_charlist("Message2")]) + :rpc.call(get_rabbit_hostname(), :logger, :error, [to_charlist("Message3")]) # This may take a long time and fail with an ExUnit timeout data = Enum.join(stream) @@ -99,7 +99,7 @@ defmodule LogTailStreamCommandTest do :ok false -> - :rpc.call(get_rabbit_hostname(), :rabbit_log, :error, [to_charlist("Ping")]) + :rpc.call(get_rabbit_hostname(), :logger, :error, [to_charlist("Ping")]) :timer.sleep(100) ensure_file(log, attempts - 1) end From 9b3f66c2eccfc6e1187f022e2327c25f42e374f3 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Tue, 15 Jul 2025 21:01:01 +0200 Subject: [PATCH 25/31] Remove rabbit_log from Makefile --- deps/rabbit/Makefile | 1 - 1 file changed, 1 deletion(-) diff --git a/deps/rabbit/Makefile b/deps/rabbit/Makefile index 7db19d2eae68..47bd7e9201b3 100644 --- a/deps/rabbit/Makefile +++ b/deps/rabbit/Makefile @@ -3,7 +3,6 @@ PROJECT_DESCRIPTION = RabbitMQ PROJECT_MOD = rabbit PROJECT_REGISTERED = rabbit_amqqueue_sup \ rabbit_direct_client_sup \ - rabbit_log \ rabbit_node_monitor \ rabbit_router From bcc062203d8e519e6e930e6fc86e9cbf24146b53 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Tue, 15 Jul 2025 21:00:52 +0200 Subject: [PATCH 26/31] rabbit_log -> logger in MQTT test --- deps/rabbitmq_mqtt/test/auth_SUITE.erl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deps/rabbitmq_mqtt/test/auth_SUITE.erl b/deps/rabbitmq_mqtt/test/auth_SUITE.erl index 94c0af330b96..38eb6718a10e 100644 --- a/deps/rabbitmq_mqtt/test/auth_SUITE.erl +++ b/deps/rabbitmq_mqtt/test/auth_SUITE.erl @@ -465,7 +465,7 @@ end_per_testcase(T, Config) when T == queue_bind_permission; T == loopback_user_connects_from_remote_host -> %% So let's wait before logs are surely flushed Marker = "MQTT_AUTH_SUITE_MARKER", - rpc(Config, 0, rabbit_log, error, [Marker]), + rpc(Config, 0, logger, error, [Marker]), wait_log(Config, [{[Marker], fun () -> stop end}]), %% Preserve file contents in case some investigation is needed, before truncating. From e459859a404dc02012690635ec0aaa5230ef318d Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Tue, 15 Jul 2025 23:21:52 +0200 Subject: [PATCH 27/31] Remove test for rabbit_log:log/4 --- .../test/diagnostics/log_location_command_test.exs | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/deps/rabbitmq_cli/test/diagnostics/log_location_command_test.exs b/deps/rabbitmq_cli/test/diagnostics/log_location_command_test.exs index 4be8a9169629..833153c2578f 100644 --- a/deps/rabbitmq_cli/test/diagnostics/log_location_command_test.exs +++ b/deps/rabbitmq_cli/test/diagnostics/log_location_command_test.exs @@ -69,16 +69,5 @@ defmodule LogLocationCommandTest do log_message = "checking the default log file when checking all" :rpc.call(get_rabbit_hostname(), :logger, :error, [to_charlist(log_message)]) wait_for_log_message(log_message, logfile) - - log_message_upgrade = "checking the upgrade log file when checking all" - - :rpc.call(get_rabbit_hostname(), :logger, :log, [ - :upgrade, - :error, - to_charlist(log_message_upgrade), - [] - ]) - - wait_for_log_message(log_message_upgrade, logfile) end end From 1e17455463b6d9e483d8b3f4c790730ad8e873fc Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Wed, 16 Jul 2025 00:06:29 +0200 Subject: [PATCH 28/31] [skip ci] Code formatting --- .../src/amqp10_client_connection.erl | 4 +- .../src/amqp10_client_frame_reader.erl | 10 ++-- .../src/amqp10_client_session.erl | 4 +- deps/amqp_client/src/amqp_channel.erl | 4 +- deps/amqp_client/src/amqp_gen_connection.erl | 4 +- deps/oauth2_client/src/oauth2_client.erl | 16 +++--- deps/rabbit/src/code_server_cache.erl | 2 +- deps/rabbit/src/mc_compat.erl | 4 +- deps/rabbit/src/pg_local.erl | 4 +- deps/rabbit/src/rabbit.erl | 2 +- deps/rabbit/src/rabbit_alarm.erl | 4 +- deps/rabbit/src/rabbit_amqp_filter_sql.erl | 10 ++-- deps/rabbit/src/rabbit_amqp_management.erl | 2 +- deps/rabbit/src/rabbit_amqqueue.erl | 8 +-- deps/rabbit/src/rabbit_amqqueue_sup_sup.erl | 4 +- .../src/rabbit_auth_backend_internal.erl | 12 ++--- deps/rabbit/src/rabbit_channel.erl | 8 +-- deps/rabbit/src/rabbit_channel_tracking.erl | 4 +- deps/rabbit/src/rabbit_classic_queue.erl | 8 +-- .../src/rabbit_classic_queue_index_v2.erl | 4 +- .../src/rabbit_classic_queue_store_v2.erl | 4 +- .../rabbit/src/rabbit_connection_tracking.erl | 10 ++-- .../src/rabbit_federation_link_util.erl | 20 ++++---- .../src/rabbit_shovel_worker.erl | 50 ++++++++++++------- 24 files changed, 109 insertions(+), 93 deletions(-) diff --git a/deps/amqp10_client/src/amqp10_client_connection.erl b/deps/amqp10_client/src/amqp10_client_connection.erl index d075c27e82cc..0ca030fafa20 100644 --- a/deps/amqp10_client/src/amqp10_client_connection.erl +++ b/deps/amqp10_client/src/amqp10_client_connection.erl @@ -249,7 +249,7 @@ hdr_sent(_EvtType, {protocol_header_received, 0, 1, 0, 0}, State) -> hdr_sent(_EvtType, {protocol_header_received, Protocol, Maj, Min, Rev}, State) -> ?LOG_WARNING("Unsupported protocol version: ~b ~b.~b.~b", - [Protocol, Maj, Min, Rev]), + [Protocol, Maj, Min, Rev]), {stop, normal, State}; hdr_sent({call, From}, begin_session, #state{pending_session_reqs = PendingSessionReqs} = State) -> @@ -344,7 +344,7 @@ opened(info, {'DOWN', MRef, process, _, _Info}, {stop, normal}; opened(_EvtType, Frame, State) -> ?LOG_WARNING("Unexpected connection frame ~tp when in state ~tp ", - [Frame, State]), + [Frame, State]), keep_state_and_data. close_sent(_EvtType, heartbeat, _Data) -> diff --git a/deps/amqp10_client/src/amqp10_client_frame_reader.erl b/deps/amqp10_client/src/amqp10_client_frame_reader.erl index 93ccf464acb4..d85af76b9415 100644 --- a/deps/amqp10_client/src/amqp10_client_frame_reader.erl +++ b/deps/amqp10_client/src/amqp10_client_frame_reader.erl @@ -143,17 +143,17 @@ handle_event(info, {gun_ws, WsPid, StreamRef, WsFrame}, StateName, handle_socket_input(Bin, StateName, State); close -> ?LOG_INFO("peer closed AMQP over WebSocket connection in state '~s'", - [StateName]), + [StateName]), {stop, normal, socket_closed(State)}; {close, ReasonStatusCode, ReasonUtf8} -> ?LOG_INFO("peer closed AMQP over WebSocket connection in state '~s', reason: ~b ~ts", - [StateName, ReasonStatusCode, ReasonUtf8]), + [StateName, ReasonStatusCode, ReasonUtf8]), {stop, {shutdown, {ReasonStatusCode, ReasonUtf8}}, socket_closed(State)} end; handle_event(info, {TcpError, _Sock, Reason}, StateName, State) when TcpError == tcp_error orelse TcpError == ssl_error -> ?LOG_WARNING("AMQP 1.0 connection socket errored, connection state: '~ts', reason: '~tp'", - [StateName, Reason]), + [StateName, Reason]), {stop, {error, Reason}, socket_closed(State)}; handle_event(info, {TcpClosed, _}, StateName, State) when TcpClosed == tcp_closed orelse TcpClosed == ssl_closed -> @@ -163,12 +163,12 @@ handle_event(info, {TcpClosed, _}, StateName, State) handle_event(info, {gun_down, WsPid, _Proto, Reason, _Streams}, StateName, #state{socket = {ws, WsPid, _StreamRef}} = State) -> ?LOG_WARNING("AMQP over WebSocket process ~p lost connection in state: '~s': ~p", - [WsPid, StateName, Reason]), + [WsPid, StateName, Reason]), {stop, Reason, socket_closed(State)}; handle_event(info, {'DOWN', _Mref, process, WsPid, Reason}, StateName, #state{socket = {ws, WsPid, _StreamRef}} = State) -> ?LOG_WARNING("AMQP over WebSocket process ~p terminated in state: '~s': ~p", - [WsPid, StateName, Reason]), + [WsPid, StateName, Reason]), {stop, Reason, socket_closed(State)}; handle_event(info, heartbeat, _StateName, #state{connection = Connection}) -> diff --git a/deps/amqp10_client/src/amqp10_client_session.erl b/deps/amqp10_client/src/amqp10_client_session.erl index 08dd5e54de43..df2d7564f555 100644 --- a/deps/amqp10_client/src/amqp10_client_session.erl +++ b/deps/amqp10_client/src/amqp10_client_session.erl @@ -487,7 +487,7 @@ mapped(cast, #'v1_0.disposition'{role = true, {keep_state, State#state{outgoing_unsettled = Unsettled}}; mapped(cast, Frame, State) -> ?LOG_WARNING("Unhandled session frame ~tp in state ~tp", - [Frame, State]), + [Frame, State]), {keep_state, State}; mapped({call, From}, {transfer, _Transfer, _Sections}, @@ -568,7 +568,7 @@ mapped({call, From}, Msg, State) -> mapped(_EvtType, Msg, _State) -> ?LOG_WARNING("amqp10_session: unhandled msg in mapped state ~W", - [Msg, 10]), + [Msg, 10]), keep_state_and_data. end_sent(_EvtType, #'v1_0.end'{} = End, State) -> diff --git a/deps/amqp_client/src/amqp_channel.erl b/deps/amqp_client/src/amqp_channel.erl index 06e9da7fc3b9..25203c73c7ca 100644 --- a/deps/amqp_client/src/amqp_channel.erl +++ b/deps/amqp_client/src/amqp_channel.erl @@ -781,8 +781,8 @@ handle_method_from_server1( State = #state{return_handler = ReturnHandler}) -> _ = case ReturnHandler of none -> ?LOG_WARNING("Channel (~tp): received {~tp, ~tp} but there is " - "no return handler registered", - [self(), BasicReturn, AmqpMsg]); + "no return handler registered", + [self(), BasicReturn, AmqpMsg]); {Pid, _Ref} -> Pid ! {BasicReturn, AmqpMsg} end, {noreply, State}; diff --git a/deps/amqp_client/src/amqp_gen_connection.erl b/deps/amqp_client/src/amqp_gen_connection.erl index 25596cc69a04..5681845779da 100644 --- a/deps/amqp_client/src/amqp_gen_connection.erl +++ b/deps/amqp_client/src/amqp_gen_connection.erl @@ -193,7 +193,7 @@ handle_cast({hard_error_in_channel, _Pid, Reason}, State) -> server_initiated_close(Reason, State); handle_cast({channel_internal_error, Pid, Reason}, State) -> ?LOG_WARNING("Connection (~tp) closing: internal error in channel (~tp): ~tp", - [self(), Pid, Reason]), + [self(), Pid, Reason]), internal_error(Pid, Reason, State); handle_cast({server_misbehaved, AmqpError}, State) -> server_misbehaved_close(AmqpError, State); @@ -324,7 +324,7 @@ server_initiated_close(Close, State) -> server_misbehaved_close(AmqpError, State) -> ?LOG_WARNING("Connection (~tp) closing: server misbehaved: ~tp", - [self(), AmqpError]), + [self(), AmqpError]), {0, Close} = rabbit_binary_generator:map_exception(0, AmqpError, ?PROTOCOL), set_closing_state(abrupt, #closing{reason = server_misbehaved, close = Close}, State). diff --git a/deps/oauth2_client/src/oauth2_client.erl b/deps/oauth2_client/src/oauth2_client.erl index 56bb085a8c9c..1aba46033d22 100644 --- a/deps/oauth2_client/src/oauth2_client.erl +++ b/deps/oauth2_client/src/oauth2_client.erl @@ -24,7 +24,7 @@ {error, unsuccessful_access_token_response() | any()}. get_access_token(OAuthProvider, Request) -> ?LOG_DEBUG("get_access_token using OAuthProvider:~p and client_id:~p", - [OAuthProvider, Request#access_token_request.client_id]), + [OAuthProvider, Request#access_token_request.client_id]), URL = OAuthProvider#oauth_provider.token_endpoint, Header = [], Type = ?CONTENT_URLENCODED, @@ -221,7 +221,7 @@ do_update_oauth_provider_endpoints_configuration(OAuthProvider) when JwksUri -> set_env(jwks_uri, JwksUri) end, ?LOG_DEBUG("Updated oauth_provider details: ~p ", - [format_oauth_provider(OAuthProvider)]), + [format_oauth_provider(OAuthProvider)]), OAuthProvider; do_update_oauth_provider_endpoints_configuration(OAuthProvider) -> @@ -273,7 +273,7 @@ get_oauth_provider(ListOfRequiredAttributes) -> undefined -> get_root_oauth_provider(ListOfRequiredAttributes); DefaultOauthProviderId -> ?LOG_DEBUG("Using default_oauth_provider ~p", - [DefaultOauthProviderId]), + [DefaultOauthProviderId]), get_oauth_provider(DefaultOauthProviderId, ListOfRequiredAttributes) end. @@ -296,7 +296,7 @@ ensure_oauth_provider_has_attributes(OAuthProvider, ListOfRequiredAttributes) -> case find_missing_attributes(OAuthProvider, ListOfRequiredAttributes) of [] -> ?LOG_DEBUG("Resolved oauth_provider ~p", - [format_oauth_provider(OAuthProvider)]), + [format_oauth_provider(OAuthProvider)]), {ok, OAuthProvider}; _ = Attrs -> {error, {missing_oauth_provider_attributes, Attrs}} @@ -305,13 +305,13 @@ ensure_oauth_provider_has_attributes(OAuthProvider, ListOfRequiredAttributes) -> get_root_oauth_provider(ListOfRequiredAttributes) -> OAuthProvider = lookup_root_oauth_provider(), ?LOG_DEBUG("Using root oauth_provider ~p", - [format_oauth_provider(OAuthProvider)]), + [format_oauth_provider(OAuthProvider)]), case find_missing_attributes(OAuthProvider, ListOfRequiredAttributes) of [] -> {ok, OAuthProvider}; _ = MissingAttributes -> ?LOG_DEBUG("Looking up missing attributes ~p ...", - [MissingAttributes]), + [MissingAttributes]), case download_oauth_provider(OAuthProvider) of {ok, OAuthProvider2} -> ensure_oauth_provider_has_attributes(OAuthProvider2, @@ -335,11 +335,11 @@ get_oauth_provider(OAuth2ProviderId, ListOfRequiredAttributes) get_oauth_provider(OAuthProviderId, ListOfRequiredAttributes) when is_binary(OAuthProviderId) -> ?LOG_DEBUG("get_oauth_provider ~p with at least these attributes: ~p", - [OAuthProviderId, ListOfRequiredAttributes]), + [OAuthProviderId, ListOfRequiredAttributes]), case lookup_oauth_provider_config(OAuthProviderId) of {error, _} = Error0 -> ?LOG_DEBUG("Failed to find oauth_provider ~p configuration due to ~p", - [OAuthProviderId, Error0]), + [OAuthProviderId, Error0]), Error0; Config -> ?LOG_DEBUG("Found oauth_provider configuration ~p", [Config]), diff --git a/deps/rabbit/src/code_server_cache.erl b/deps/rabbit/src/code_server_cache.erl index f9e516bbef92..3d3f750ad68e 100644 --- a/deps/rabbit/src/code_server_cache.erl +++ b/deps/rabbit/src/code_server_cache.erl @@ -73,7 +73,7 @@ handle_maybe_call_mfa(true, {Module, Function, Args, Default}, State) -> handle_maybe_call_mfa_error(Module, Default, State); Err:Reason -> ?LOG_ERROR("Calling ~tp:~tp failed: ~tp:~tp", - [Module, Function, Err, Reason]), + [Module, Function, Err, Reason]), handle_maybe_call_mfa_error(Module, Default, State) end. diff --git a/deps/rabbit/src/mc_compat.erl b/deps/rabbit/src/mc_compat.erl index 1f11bc4bfef4..f501327c4b7b 100644 --- a/deps/rabbit/src/mc_compat.erl +++ b/deps/rabbit/src/mc_compat.erl @@ -269,8 +269,8 @@ update_x_death_header(Info, Headers) -> [{table, rabbit_misc:sort_field_table(Info1)} | Others]); {<<"x-death">>, InvalidType, Header} -> ?LOG_WARNING("Message has invalid x-death header (type: ~tp)." - " Resetting header ~tp", - [InvalidType, Header]), + " Resetting header ~tp", + [InvalidType, Header]), %% if x-death is something other than an array (list) %% then we reset it: this happens when some clients consume %% a message and re-publish is, converting header values diff --git a/deps/rabbit/src/pg_local.erl b/deps/rabbit/src/pg_local.erl index c3e019954bda..6397ea69a5c0 100644 --- a/deps/rabbit/src/pg_local.erl +++ b/deps/rabbit/src/pg_local.erl @@ -123,8 +123,8 @@ handle_call(clear, _From, S) -> handle_call(Request, From, S) -> ?LOG_WARNING("The pg_local server received an unexpected message:\n" - "handle_call(~tp, ~tp, _)\n", - [Request, From]), + "handle_call(~tp, ~tp, _)\n", + [Request, From]), {noreply, S}. handle_cast({join, Name, Pid}, S) -> diff --git a/deps/rabbit/src/rabbit.erl b/deps/rabbit/src/rabbit.erl index 86e74f763fef..6224c7012761 100644 --- a/deps/rabbit/src/rabbit.erl +++ b/deps/rabbit/src/rabbit.erl @@ -1155,7 +1155,7 @@ pg_local_scope(Prefix) -> update_cluster_tags() -> Tags = application:get_env(rabbit, cluster_tags, []), ?LOG_DEBUG("Seeding cluster tags from application environment key...", - #{domain => ?RMQLOG_DOMAIN_GLOBAL}), + #{domain => ?RMQLOG_DOMAIN_GLOBAL}), rabbit_runtime_parameters:set_global(cluster_tags, Tags, <<"internal_user">>). diff --git a/deps/rabbit/src/rabbit_alarm.erl b/deps/rabbit/src/rabbit_alarm.erl index 969e614f4a59..879fdae81896 100644 --- a/deps/rabbit/src/rabbit_alarm.erl +++ b/deps/rabbit/src/rabbit_alarm.erl @@ -242,7 +242,7 @@ handle_event({node_down, Node}, #alarms{alarmed_nodes = AN} = State) -> end, {ok, lists:foldr(fun(Source, AccState) -> ?LOG_WARNING("~ts resource limit alarm cleared for dead node ~tp", - [Source, Node]), + [Source, Node]), maybe_alert(fun dict_unappend/3, Node, Source, false, AccState) end, State, AlarmsForDeadNode)}; @@ -350,7 +350,7 @@ handle_set_alarm(Alarm, State) -> handle_clear_resource_alarm(Source, Node, State) -> ?LOG_WARNING("~ts resource limit alarm cleared on node ~tp", - [Source, Node]), + [Source, Node]), {ok, maybe_alert(fun dict_unappend/3, Node, Source, false, State)}. handle_clear_alarm(file_descriptor_limit, State) -> diff --git a/deps/rabbit/src/rabbit_amqp_filter_sql.erl b/deps/rabbit/src/rabbit_amqp_filter_sql.erl index 25341719dcde..e1a34ec0073d 100644 --- a/deps/rabbit/src/rabbit_amqp_filter_sql.erl +++ b/deps/rabbit/src/rabbit_amqp_filter_sql.erl @@ -295,14 +295,14 @@ sql_to_list(SQL) -> {ok, String}; Error -> ?LOG_WARNING("JMS message selector ~p is not UTF-8 encoded: ~p", - [JmsSelector, Error]), + [JmsSelector, Error]), error end. check_length(String) when length(String) > ?MAX_EXPRESSION_LENGTH -> ?LOG_WARNING("JMS message selector length ~b exceeds maximum length ~b", - [length(String), ?MAX_EXPRESSION_LENGTH]), + [length(String), ?MAX_EXPRESSION_LENGTH]), error; check_length(_) -> ok. @@ -313,14 +313,14 @@ tokenize(String, SQL) -> {ok, Tokens}; {error, {_Line, _Mod, ErrDescriptor}, _Location} -> ?LOG_WARNING("failed to scan JMS message selector '~ts': ~tp", - [JmsSelector, ErrDescriptor]), + [JmsSelector, ErrDescriptor]), error end. check_token_count(Tokens, SQL) when length(Tokens) > ?MAX_TOKENS -> ?LOG_WARNING("JMS message selector '~ts' with ~b tokens exceeds token limit ~b", - [JmsSelector, length(Tokens), ?MAX_TOKENS]), + [JmsSelector, length(Tokens), ?MAX_TOKENS]), error; check_token_count(_, _) -> ok. @@ -329,7 +329,7 @@ parse(Tokens, SQL) -> case rabbit_amqp_sql_parser:parse(Tokens) of {error, Reason} -> ?LOG_WARNING("failed to parse JMS message selector '~ts': ~p", - [JmsSelector, Reason]), + [JmsSelector, Reason]), error; Ok -> Ok diff --git a/deps/rabbit/src/rabbit_amqp_management.erl b/deps/rabbit/src/rabbit_amqp_management.erl index 7769c7c7327f..dde44bb7d9bb 100644 --- a/deps/rabbit/src/rabbit_amqp_management.erl +++ b/deps/rabbit/src/rabbit_amqp_management.erl @@ -51,7 +51,7 @@ handle_request(Request, Vhost, User, ConnectionPid, PermCaches0) -> PermCaches0) catch throw:{?MODULE, StatusCode0, Explanation} -> ?LOG_WARNING("request ~ts ~ts failed: ~ts", - [HttpMethod, HttpRequestTarget, Explanation]), + [HttpMethod, HttpRequestTarget, Explanation]), {StatusCode0, {utf8, Explanation}, PermCaches0} end, diff --git a/deps/rabbit/src/rabbit_amqqueue.erl b/deps/rabbit/src/rabbit_amqqueue.erl index 041cb52cc75f..3bb8f53f3bff 100644 --- a/deps/rabbit/src/rabbit_amqqueue.erl +++ b/deps/rabbit/src/rabbit_amqqueue.erl @@ -425,7 +425,7 @@ rebalance(Type, VhostSpec, QueueSpec) -> %% filtered out with is_replicable(Q). Maybe error instead? maybe_rebalance({true, Id}, Type, VhostSpec, QueueSpec) -> ?LOG_INFO("Starting queue rebalance operation: '~ts' for vhosts matching '~ts' and queues matching '~ts'", - [Type, VhostSpec, QueueSpec]), + [Type, VhostSpec, QueueSpec]), Running = rabbit_maintenance:filter_out_drained_nodes_consistent_read(rabbit_nodes:list_running()), NumRunning = length(Running), TypeModule = case Type of @@ -523,7 +523,7 @@ maybe_migrate(ByNode, MaxQueuesDesired, [N | Nodes]) -> _ -> [{Length, Destination} | _] = sort_by_number_of_queues(Candidates, ByNode), ?LOG_INFO("Migrating queue ~tp from node ~tp with ~tp queues to node ~tp with ~tp queues", - [Name, N, length(All), Destination, Length]), + [Name, N, length(All), Destination, Length]), case Module:transfer_leadership(Q, Destination) of {migrated, NewNode} -> ?LOG_INFO("Queue ~tp migrated to ~tp", [Name, NewNode]), @@ -1982,8 +1982,8 @@ delete_transient_queues_on_node(Node) -> case length(QueueNames) of 0 -> ok; N -> ?LOG_INFO("~b transient queues from node '~ts' " - "deleted in ~fs", - [N, Node, Time / 1_000_000]) + "deleted in ~fs", + [N, Node, Time / 1_000_000]) end, notify_queue_binding_deletions(Deletions), rabbit_core_metrics:queues_deleted(QueueNames), diff --git a/deps/rabbit/src/rabbit_amqqueue_sup_sup.erl b/deps/rabbit/src/rabbit_amqqueue_sup_sup.erl index e7cba35f5905..1394a518780d 100644 --- a/deps/rabbit/src/rabbit_amqqueue_sup_sup.erl +++ b/deps/rabbit/src/rabbit_amqqueue_sup_sup.erl @@ -76,7 +76,7 @@ start_for_vhost(VHost) -> %% e.g. some integration tests do it {error, {no_such_vhost, VHost}} -> ?LOG_ERROR("Failed to start a queue process supervisor for vhost ~ts: vhost no longer exists!", - [VHost]), + [VHost]), {error, {no_such_vhost, VHost}} end. @@ -89,6 +89,6 @@ stop_for_vhost(VHost) -> %% see start/1 {error, {no_such_vhost, VHost}} -> ?LOG_ERROR("Failed to stop a queue process supervisor for vhost ~ts: vhost no longer exists!", - [VHost]), + [VHost]), ok end. diff --git a/deps/rabbit/src/rabbit_auth_backend_internal.erl b/deps/rabbit/src/rabbit_auth_backend_internal.erl index 4b658f7794f6..09bf96f6a192 100644 --- a/deps/rabbit/src/rabbit_auth_backend_internal.erl +++ b/deps/rabbit/src/rabbit_auth_backend_internal.erl @@ -526,11 +526,11 @@ set_permissions(Username, VirtualHost, ConfigurePerm, WritePerm, ReadPerm, Actin clear_permissions(Username, VirtualHost, ActingUser) -> ?LOG_DEBUG("Asked to clear permissions for user '~ts' in virtual host '~ts'", - [Username, VirtualHost]), + [Username, VirtualHost]), try R = rabbit_db_user:clear_user_permissions(Username, VirtualHost), ?LOG_INFO("Successfully cleared permissions for user '~ts' in virtual host '~ts'", - [Username, VirtualHost]), + [Username, VirtualHost]), rabbit_event:notify(permission_deleted, [{user, Username}, {vhost, VirtualHost}, {user_who_performed_action, ActingUser}]), @@ -636,11 +636,11 @@ set_topic_permissions(Username, VirtualHost, Exchange, WritePerm, ReadPerm, Acti clear_topic_permissions(Username, VirtualHost, ActingUser) -> ?LOG_DEBUG("Asked to clear topic permissions for user '~ts' in virtual host '~ts'", - [Username, VirtualHost]), + [Username, VirtualHost]), try R = rabbit_db_user:clear_topic_permissions(Username, VirtualHost, '_'), ?LOG_INFO("Successfully cleared topic permissions for user '~ts' in virtual host '~ts'", - [Username, VirtualHost]), + [Username, VirtualHost]), rabbit_event:notify(topic_permission_deleted, [{user, Username}, {vhost, VirtualHost}, {user_who_performed_action, ActingUser}]), @@ -654,12 +654,12 @@ clear_topic_permissions(Username, VirtualHost, ActingUser) -> clear_topic_permissions(Username, VirtualHost, Exchange, ActingUser) -> ?LOG_DEBUG("Asked to clear topic permissions on exchange '~ts' for user '~ts' in virtual host '~ts'", - [Exchange, Username, VirtualHost]), + [Exchange, Username, VirtualHost]), try R = rabbit_db_user:clear_topic_permissions( Username, VirtualHost, Exchange), ?LOG_INFO("Successfully cleared topic permissions on exchange '~ts' for user '~ts' in virtual host '~ts'", - [Exchange, Username, VirtualHost]), + [Exchange, Username, VirtualHost]), rabbit_event:notify(topic_permission_deleted, [{user, Username}, {vhost, VirtualHost}, {user_who_performed_action, ActingUser}]), diff --git a/deps/rabbit/src/rabbit_channel.erl b/deps/rabbit/src/rabbit_channel.erl index 649270bc7d1e..6ee0dec45d00 100644 --- a/deps/rabbit/src/rabbit_channel.erl +++ b/deps/rabbit/src/rabbit_channel.erl @@ -414,8 +414,8 @@ refresh_config_local() -> gen_server2:call(C, refresh_config, infinity) catch _:Reason -> ?LOG_ERROR("Failed to refresh channel config " - "for channel ~tp. Reason ~tp", - [C, Reason]) + "for channel ~tp. Reason ~tp", + [C, Reason]) end end, list_local()), @@ -428,8 +428,8 @@ refresh_interceptors() -> gen_server2:call(C, refresh_interceptors, ?REFRESH_TIMEOUT) catch _:Reason -> ?LOG_ERROR("Failed to refresh channel interceptors " - "for channel ~tp. Reason ~tp", - [C, Reason]) + "for channel ~tp. Reason ~tp", + [C, Reason]) end end, list_local()), diff --git a/deps/rabbit/src/rabbit_channel_tracking.erl b/deps/rabbit/src/rabbit_channel_tracking.erl index 1c4ede34fe37..7843d9a3c44a 100644 --- a/deps/rabbit/src/rabbit_channel_tracking.erl +++ b/deps/rabbit/src/rabbit_channel_tracking.erl @@ -219,13 +219,13 @@ ensure_tracked_tables_for_this_node() -> %% Create tables ensure_tracked_channels_table_for_this_node() -> ?LOG_INFO("Setting up a table for channel tracking on this node: ~tp", - [?TRACKED_CHANNEL_TABLE]), + [?TRACKED_CHANNEL_TABLE]), ets:new(?TRACKED_CHANNEL_TABLE, [named_table, public, {write_concurrency, true}, {keypos, #tracked_channel.pid}]). ensure_per_user_tracked_channels_table_for_this_node() -> ?LOG_INFO("Setting up a table for channel tracking on this node: ~tp", - [?TRACKED_CHANNEL_TABLE_PER_USER]), + [?TRACKED_CHANNEL_TABLE_PER_USER]), ets:new(?TRACKED_CHANNEL_TABLE_PER_USER, [named_table, public, {write_concurrency, true}]). get_tracked_channels_by_connection_pid(ConnPid) -> diff --git a/deps/rabbit/src/rabbit_classic_queue.erl b/deps/rabbit/src/rabbit_classic_queue.erl index 125a95173a0f..ed7c5619d58d 100644 --- a/deps/rabbit/src/rabbit_classic_queue.erl +++ b/deps/rabbit/src/rabbit_classic_queue.erl @@ -179,9 +179,9 @@ delete(Q0, IfUnused, IfEmpty, ActingUser) when ?amqqueue_is_classic(Q0) -> case IfEmpty of true -> ?LOG_ERROR("Queue ~ts in vhost ~ts is down. " - "The queue may be non-empty. " - "Refusing to force-delete.", - [Name, Vhost]), + "The queue may be non-empty. " + "Refusing to force-delete.", + [Name, Vhost]), {error, not_empty}; false -> ?LOG_WARNING("Queue ~ts in vhost ~ts is down. " @@ -590,7 +590,7 @@ recover_durable_queues(QueuesAndRecoveryTerms) -> [{rabbit_amqqueue_sup_sup:start_queue_process(node(), Q), {init, {self(), Terms}}} || {Q, Terms} <- QueuesAndRecoveryTerms]), _ = [?LOG_ERROR("Queue ~tp failed to initialise: ~tp", - [Pid, Error]) || {Pid, Error} <- Failures], + [Pid, Error]) || {Pid, Error} <- Failures], [Q || {_, {new, Q}} <- Results]. capabilities() -> diff --git a/deps/rabbit/src/rabbit_classic_queue_index_v2.erl b/deps/rabbit/src/rabbit_classic_queue_index_v2.erl index 855b77e635f4..7d6fa3de8aea 100644 --- a/deps/rabbit/src/rabbit_classic_queue_index_v2.erl +++ b/deps/rabbit/src/rabbit_classic_queue_index_v2.erl @@ -447,7 +447,7 @@ recover_index_v1_clean(State0 = #qi{ queue_name = Name }, Terms, IsMsgStoreClean CountersRef = counters:new(?RECOVER_COUNTER_SIZE, []), State = recover_index_v1_common(State0, V1State, CountersRef), ?LOG_INFO("Queue ~ts in vhost ~ts converted ~b total messages from v1 to v2", - [QName, VHost, counters:get(CountersRef, ?RECOVER_COUNT)]), + [QName, VHost, counters:get(CountersRef, ?RECOVER_COUNT)]), State. recover_index_v1_dirty(State0 = #qi{ queue_name = Name }, Terms, IsMsgStoreClean, @@ -466,7 +466,7 @@ recover_index_v1_dirty(State0 = #qi{ queue_name = Name }, Terms, IsMsgStoreClean convert), State = recover_index_v1_common(State0, V1State, CountersRef), ?LOG_INFO("Queue ~ts in vhost ~ts converted ~b total messages from v1 to v2", - [QName, VHost, counters:get(CountersRef, ?RECOVER_COUNT)]), + [QName, VHost, counters:get(CountersRef, ?RECOVER_COUNT)]), State. %% At this point all messages are persistent because transient messages diff --git a/deps/rabbit/src/rabbit_classic_queue_store_v2.erl b/deps/rabbit/src/rabbit_classic_queue_store_v2.erl index d324acf26ff6..9e27c7c25193 100644 --- a/deps/rabbit/src/rabbit_classic_queue_store_v2.erl +++ b/deps/rabbit/src/rabbit_classic_queue_store_v2.erl @@ -319,7 +319,7 @@ read_from_disk(SeqId, {?MODULE, Offset, Size}, State0) -> ok catch C:E:S -> ?LOG_ERROR("Per-queue store CRC32 check failed in ~ts seq id ~b offset ~b size ~b", - [segment_file(Segment, State), SeqId, Offset, Size]), + [segment_file(Segment, State), SeqId, Offset, Size]), erlang:raise(C, E, S) end end, @@ -417,7 +417,7 @@ parse_many_from_disk([< ?LOG_ERROR("Per-queue store CRC32 check failed in ~ts", - [segment_file(Segment, State)]), + [segment_file(Segment, State)]), erlang:raise(C, E, S) end end, diff --git a/deps/rabbit/src/rabbit_connection_tracking.erl b/deps/rabbit/src/rabbit_connection_tracking.erl index f38e982451a6..74ae63ece812 100644 --- a/deps/rabbit/src/rabbit_connection_tracking.erl +++ b/deps/rabbit/src/rabbit_connection_tracking.erl @@ -118,8 +118,8 @@ handle_cast({vhost_down, Details}) -> VHost = pget(name, Details), Node = pget(node, Details), ?LOG_INFO("Closing all connections in vhost '~ts' on node '~ts'" - " because the vhost is stopping", - [VHost, Node]), + " because the vhost is stopping", + [VHost, Node]), shutdown_tracked_items( list_on_node(Node, VHost), rabbit_misc:format("vhost '~ts' is down", [VHost])); @@ -191,17 +191,17 @@ ensure_tracked_connections_table_for_this_node() -> _ = ets:new(?TRACKED_CONNECTION_TABLE, [named_table, public, {write_concurrency, true}, {keypos, #tracked_connection.id}]), ?LOG_INFO("Setting up a table for connection tracking on this node: ~tp", - [?TRACKED_CONNECTION_TABLE]). + [?TRACKED_CONNECTION_TABLE]). ensure_per_vhost_tracked_connections_table_for_this_node() -> ?LOG_INFO("Setting up a table for per-vhost connection counting on this node: ~tp", - [?TRACKED_CONNECTION_TABLE_PER_VHOST]), + [?TRACKED_CONNECTION_TABLE_PER_VHOST]), ets:new(?TRACKED_CONNECTION_TABLE_PER_VHOST, [named_table, public, {write_concurrency, true}]). ensure_per_user_tracked_connections_table_for_this_node() -> _ = ets:new(?TRACKED_CONNECTION_TABLE_PER_USER, [named_table, public, {write_concurrency, true}]), ?LOG_INFO("Setting up a table for per-user connection counting on this node: ~tp", - [?TRACKED_CONNECTION_TABLE_PER_USER]). + [?TRACKED_CONNECTION_TABLE_PER_USER]). -spec tracked_connection_table_name_for(node()) -> atom(). diff --git a/deps/rabbitmq_federation_common/src/rabbit_federation_link_util.erl b/deps/rabbitmq_federation_common/src/rabbit_federation_link_util.erl index e2d72d38a6c7..b42cb731bf3d 100644 --- a/deps/rabbitmq_federation_common/src/rabbit_federation_link_util.erl +++ b/deps/rabbitmq_federation_common/src/rabbit_federation_link_util.erl @@ -56,8 +56,8 @@ start_conn_ch(Fun, OUpstream, OUParams, try R = Fun(Conn, Ch, DConn, DCh), ?LOG_INFO("Federation ~ts connected to ~ts", - [rabbit_misc:rs(XorQName), - rabbit_federation_upstream:params_to_string(UParams)]), + [rabbit_misc:rs(XorQName), + rabbit_federation_upstream:params_to_string(UParams)]), Name = pget(name, amqp_connection:info(DConn, [name])), rabbit_federation_status:report( OUpstream, OUParams, XorQName, {running, Name}), @@ -130,31 +130,31 @@ connection_error(remote_start, {{shutdown, {server_initiated_close, Code, Messag rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(E)), ?LOG_WARNING("Federation ~ts did not connect to ~ts. Server has closed the connection due to an error, code: ~tp, " - "message: ~ts", - [rabbit_misc:rs(XorQName), rabbit_federation_upstream:params_to_string(UParams), - Code, Message]), + "message: ~ts", + [rabbit_misc:rs(XorQName), rabbit_federation_upstream:params_to_string(UParams), + Code, Message]), {stop, {shutdown, restart}, State}; connection_error(remote_start, E, Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(E)), ?LOG_WARNING("Federation ~ts did not connect to ~ts. Reason: ~tp", - [rabbit_misc:rs(XorQName), rabbit_federation_upstream:params_to_string(UParams), - E]), + [rabbit_misc:rs(XorQName), rabbit_federation_upstream:params_to_string(UParams), + E]), {stop, {shutdown, restart}, State}; connection_error(remote, E, Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(E)), ?LOG_INFO("Federation ~ts disconnected from ~ts~n~tp", - [rabbit_misc:rs(XorQName), rabbit_federation_upstream:params_to_string(UParams), E]), + [rabbit_misc:rs(XorQName), rabbit_federation_upstream:params_to_string(UParams), E]), {stop, {shutdown, restart}, State}; connection_error(command_channel, E, Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(E)), ?LOG_INFO("Federation ~ts failed to open a command channel for upstream ~ts~n~tp", - [rabbit_misc:rs(XorQName), rabbit_federation_upstream:params_to_string(UParams), E]), + [rabbit_misc:rs(XorQName), rabbit_federation_upstream:params_to_string(UParams), E]), {stop, {shutdown, restart}, State}; connection_error(local, basic_cancel, Upstream, UParams, XorQName, State) -> @@ -284,7 +284,7 @@ log_terminate(shutdown, Upstream, UParams, XorQName) -> %% nicely so that we do not cause unacked messages to be %% redelivered. ?LOG_INFO("disconnecting from ~ts", - [rabbit_federation_upstream:params_to_string(UParams)]), + [rabbit_federation_upstream:params_to_string(UParams)]), rabbit_federation_status:remove(Upstream, XorQName); log_terminate(Reason, Upstream, UParams, XorQName) -> diff --git a/deps/rabbitmq_shovel/src/rabbit_shovel_worker.erl b/deps/rabbitmq_shovel/src/rabbit_shovel_worker.erl index 6ea948dee1d0..368bb60ec622 100644 --- a/deps/rabbitmq_shovel/src/rabbit_shovel_worker.erl +++ b/deps/rabbitmq_shovel/src/rabbit_shovel_worker.erl @@ -77,7 +77,8 @@ handle_cast(init, State = #state{config = Config0}) -> gen_server2:cast(self(), connect_dest), {noreply, State#state{config = Config}} catch E:R -> - ?LOG_ERROR("Shovel ~ts could not connect to source: ~p ~p", [human_readable_name(maps:get(name, Config0)), E, R]), + ?LOG_ERROR("Shovel ~ts could not connect to source: ~p ~p", + [human_readable_name(maps:get(name, Config0)), E, R]), {stop, shutdown, State} end; handle_cast(connect_dest, State = #state{config = Config0}) -> @@ -87,7 +88,8 @@ handle_cast(connect_dest, State = #state{config = Config0}) -> gen_server2:cast(self(), init_shovel), {noreply, State#state{config = Config}} catch E:R -> - ?LOG_ERROR("Shovel ~ts could not connect to destination: ~p ~p", [human_readable_name(maps:get(name, Config0)), E, R]), + ?LOG_ERROR("Shovel ~ts could not connect to destination: ~p ~p", + [human_readable_name(maps:get(name, Config0)), E, R]), {stop, shutdown, State} end; handle_cast(init_shovel, State = #state{config = Config}) -> @@ -97,7 +99,8 @@ handle_cast(init_shovel, State = #state{config = Config}) -> process_flag(trap_exit, true), Config1 = rabbit_shovel_behaviour:init_dest(Config), Config2 = rabbit_shovel_behaviour:init_source(Config1), - ?LOG_DEBUG("Shovel ~ts has finished setting up its topology", [human_readable_name(maps:get(name, Config2))]), + ?LOG_DEBUG("Shovel ~ts has finished setting up its topology", + [human_readable_name(maps:get(name, Config2))]), State1 = State#state{config = Config2}, ok = report_running(State1), {noreply, State1}. @@ -108,19 +111,24 @@ handle_info(Msg, State = #state{config = Config, name = Name}) -> not_handled -> case rabbit_shovel_behaviour:handle_dest(Msg, Config) of not_handled -> - ?LOG_WARNING("Shovel ~ts could not handle a destination message ~tp", [human_readable_name(Name), Msg]), + ?LOG_WARNING("Shovel ~ts could not handle a destination message ~tp", + [human_readable_name(Name), Msg]), {noreply, State}; {stop, {outbound_conn_died, heartbeat_timeout}} -> - ?LOG_ERROR("Shovel ~ts detected missed heartbeats on destination connection", [human_readable_name(Name)]), + ?LOG_ERROR("Shovel ~ts detected missed heartbeats on destination connection", + [human_readable_name(Name)]), {stop, {shutdown, heartbeat_timeout}, State}; {stop, {outbound_conn_died, Reason}} -> - ?LOG_ERROR("Shovel ~ts detected destination connection failure: ~tp", [human_readable_name(Name), Reason]), + ?LOG_ERROR("Shovel ~ts detected destination connection failure: ~tp", + [human_readable_name(Name), Reason]), {stop, Reason, State}; {stop, {outbound_link_or_channel_closure, Reason}} -> - ?LOG_ERROR("Shovel ~ts detected destination shovel failure: ~tp", [human_readable_name(Name), Reason]), + ?LOG_ERROR("Shovel ~ts detected destination shovel failure: ~tp", + [human_readable_name(Name), Reason]), {stop, Reason, State}; {stop, Reason} -> - ?LOG_DEBUG("Shovel ~ts decided to stop due a message from destination: ~tp", [human_readable_name(Name), Reason]), + ?LOG_DEBUG("Shovel ~ts decided to stop due a message from destination: ~tp", + [human_readable_name(Name), Reason]), {stop, Reason, State}; Config1 -> State1 = State#state{config = Config1}, @@ -128,16 +136,20 @@ handle_info(Msg, State = #state{config = Config, name = Name}) -> {noreply, State2} end; {stop, {inbound_conn_died, heartbeat_timeout}} -> - ?LOG_ERROR("Shovel ~ts detected missed heartbeats on source connection", [human_readable_name(Name)]), + ?LOG_ERROR("Shovel ~ts detected missed heartbeats on source connection", + [human_readable_name(Name)]), {stop, {shutdown, heartbeat_timeout}, State}; {stop, {inbound_conn_died, Reason}} -> - ?LOG_ERROR("Shovel ~ts detected source connection failure: ~tp", [human_readable_name(Name), Reason]), + ?LOG_ERROR("Shovel ~ts detected source connection failure: ~tp", + [human_readable_name(Name), Reason]), {stop, Reason, State}; {stop, {inbound_link_or_channel_closure, Reason}} -> - ?LOG_ERROR("Shovel ~ts detected source Shovel (or link, or channel) failure: ~tp", [human_readable_name(Name), Reason]), + ?LOG_ERROR("Shovel ~ts detected source Shovel (or link, or channel) failure: ~tp", + [human_readable_name(Name), Reason]), {stop, Reason, State}; {stop, Reason} -> - ?LOG_ERROR("Shovel ~ts decided to stop due a message from source: ~tp", [human_readable_name(Name), Reason]), + ?LOG_ERROR("Shovel ~ts decided to stop due a message from source: ~tp", + [human_readable_name(Name), Reason]), {stop, Reason, State}; Config1 -> State1 = State#state{config = Config1}, @@ -149,7 +161,7 @@ terminate({shutdown, autodelete}, State = #state{name = Name, type = dynamic}) -> {VHost, ShovelName} = Name, ?LOG_INFO("Shovel '~ts' is stopping (it was configured to autodelete and transfer is completed)", - [human_readable_name(Name)]), + [human_readable_name(Name)]), close_connections(State), %% See rabbit_shovel_dyn_worker_sup_sup:stop_child/1 put({shovel_worker_autodelete, Name}, true), @@ -161,25 +173,29 @@ terminate(shutdown, State = #state{name = Name}) -> rabbit_shovel_status:remove(Name), ok; terminate(socket_closed_unexpectedly, State = #state{name = Name}) -> - ?LOG_ERROR("Shovel ~ts is stopping because of the socket closed unexpectedly", [human_readable_name(Name)]), + ?LOG_ERROR("Shovel ~ts is stopping because of the socket closed unexpectedly", + [human_readable_name(Name)]), rabbit_shovel_status:report(State#state.name, State#state.type, {terminated, "socket closed"}), close_connections(State), ok; terminate({'EXIT', heartbeat_timeout}, State = #state{name = Name}) -> - ?LOG_ERROR("Shovel ~ts is stopping because of a heartbeat timeout", [human_readable_name(Name)]), + ?LOG_ERROR("Shovel ~ts is stopping because of a heartbeat timeout", + [human_readable_name(Name)]), rabbit_shovel_status:report(State#state.name, State#state.type, {terminated, "heartbeat timeout"}), close_connections(State), ok; terminate({'EXIT', outbound_conn_died}, State = #state{name = Name}) -> - ?LOG_ERROR("Shovel ~ts is stopping because destination connection failed", [human_readable_name(Name)]), + ?LOG_ERROR("Shovel ~ts is stopping because destination connection failed", + [human_readable_name(Name)]), rabbit_shovel_status:report(State#state.name, State#state.type, {terminated, "destination connection failed"}), close_connections(State), ok; terminate({'EXIT', inbound_conn_died}, State = #state{name = Name}) -> - ?LOG_ERROR("Shovel ~ts is stopping because destination connection failed", [human_readable_name(Name)]), + ?LOG_ERROR("Shovel ~ts is stopping because destination connection failed", + [human_readable_name(Name)]), rabbit_shovel_status:report(State#state.name, State#state.type, {terminated, "source connection failed"}), close_connections(State), From 69b97b8a171358f1588be836f32748631652abf9 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Wed, 16 Jul 2025 15:56:49 +0200 Subject: [PATCH 29/31] Trigger CI From f6e718c599a6b947487d7f14dd220f82020ce096 Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Thu, 17 Jul 2025 13:05:21 +0200 Subject: [PATCH 30/31] Re-introduce rabbit_log for backwards compatibility Some community plugins use rabbit_log. To simplify the transition, we can keep this module as a simple wrapper on logger macros. --- deps/rabbit_common/src/rabbit_log.erl | 159 ++++++++++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 deps/rabbit_common/src/rabbit_log.erl diff --git a/deps/rabbit_common/src/rabbit_log.erl b/deps/rabbit_common/src/rabbit_log.erl new file mode 100644 index 000000000000..a8988a6730bf --- /dev/null +++ b/deps/rabbit_common/src/rabbit_log.erl @@ -0,0 +1,159 @@ +%% This Source Code Form is subject to the terms of the Mozilla Public +%% License, v. 2.0. If a copy of the MPL was not distributed with this +%% file, You can obtain one at https://mozilla.org/MPL/2.0/. +%% +%% Copyright (c) 2007-2025 Broadcom. All Rights Reserved. The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. All rights reserved. +%% + +-module(rabbit_log). + +-export([log/3, log/4]). +-export([debug/1, debug/2, debug/3, + info/1, info/2, info/3, + notice/1, notice/2, notice/3, + warning/1, warning/2, warning/3, + error/1, error/2, error/3, + critical/1, critical/2, critical/3, + alert/1, alert/2, alert/3, + emergency/1, emergency/2, emergency/3, + none/1, none/2, none/3]). + +-include("logging.hrl"). +-include_lib("kernel/include/logger.hrl"). + +-compile({no_auto_import, [error/2, error/3]}). + +%%---------------------------------------------------------------------------- +%% This module is deprecated and only here for backwards compatibility. +%% New code should use Erlang logger directly, usually through ?LOG_* macros. +%%---------------------------------------------------------------------------- + +-deprecated({log, 3, "Use logger:log/3 instead"}). +-deprecated({log, 4, "Use logger:log/4 instead"}). + +-deprecated({debug, 1, "Use ?LOG_DEBUG instead"}). +-deprecated({debug, 2, "Use ?LOG_DEBUG instead"}). +-deprecated({debug, 3, "Use ?LOG_DEBUG instead"}). + +-deprecated({info, 1, "Use ?LOG_INFO instead"}). +-deprecated({info, 2, "Use ?LOG_INFO instead"}). +-deprecated({info, 3, "Use ?LOG_INFO instead"}). + +-deprecated({notice, 1, "Use ?LOG_NOTICE instead"}). +-deprecated({notice, 2, "Use ?LOG_NOTICE instead"}). +-deprecated({notice, 3, "Use ?LOG_NOTICE instead"}). + +-deprecated({warning, 1, "Use ?LOG_WARNING instead"}). +-deprecated({warning, 2, "Use ?LOG_WARNING instead"}). +-deprecated({warning, 3, "Use ?LOG_WARNING instead"}). + +-deprecated({error, 1, "Use ?LOG_ERROR instead"}). +-deprecated({error, 2, "Use ?LOG_ERROR instead"}). +-deprecated({error, 3, "Use ?LOG_ERROR instead"}). + +-deprecated({critical, 1, "Use ?LOG_CRITICAL instead"}). +-deprecated({critical, 2, "Use ?LOG_CRITICAL instead"}). +-deprecated({critical, 3, "Use ?LOG_CRITICAL instead"}). + +-deprecated({emergency, 1, "Use ?LOG_EMERGENCY instead"}). +-deprecated({emergency, 2, "Use ?LOG_EMERGENCY instead"}). +-deprecated({emergency, 3, "Use ?LOG_EMERGENCY instead"}). + +-deprecated({none, 1, "Deprecated"}). +-deprecated({none, 2, "Deprecated"}). +-deprecated({none, 3, "Deprecated"}). + +%%---------------------------------------------------------------------------- + +-type category() :: atom(). + +-spec debug(string()) -> 'ok'. +-spec debug(string(), [any()]) -> 'ok'. +-spec debug(pid() | [tuple()], string(), [any()]) -> 'ok'. +-spec info(string()) -> 'ok'. +-spec info(string(), [any()]) -> 'ok'. +-spec info(pid() | [tuple()], string(), [any()]) -> 'ok'. +-spec notice(string()) -> 'ok'. +-spec notice(string(), [any()]) -> 'ok'. +-spec notice(pid() | [tuple()], string(), [any()]) -> 'ok'. +-spec warning(string()) -> 'ok'. +-spec warning(string(), [any()]) -> 'ok'. +-spec warning(pid() | [tuple()], string(), [any()]) -> 'ok'. +-spec error(string()) -> 'ok'. +-spec error(string(), [any()]) -> 'ok'. +-spec error(pid() | [tuple()], string(), [any()]) -> 'ok'. +-spec critical(string()) -> 'ok'. +-spec critical(string(), [any()]) -> 'ok'. +-spec critical(pid() | [tuple()], string(), [any()]) -> 'ok'. +-spec alert(string()) -> 'ok'. +-spec alert(string(), [any()]) -> 'ok'. +-spec alert(pid() | [tuple()], string(), [any()]) -> 'ok'. +-spec emergency(string()) -> 'ok'. +-spec emergency(string(), [any()]) -> 'ok'. +-spec emergency(pid() | [tuple()], string(), [any()]) -> 'ok'. +-spec none(string()) -> 'ok'. +-spec none(string(), [any()]) -> 'ok'. +-spec none(pid() | [tuple()], string(), [any()]) -> 'ok'. + +%%---------------------------------------------------------------------------- + +-spec log(category(), logger:level(), string()) -> 'ok'. +log(Category, Level, Fmt) -> log(Category, Level, Fmt, []). + +-spec log(category(), logger:level(), string(), [any()]) -> 'ok'. +log(default, Level, Fmt, Args) when is_list(Args) -> + logger:log(Level, Fmt, Args, #{domain => ?RMQLOG_DOMAIN_GLOBAL}); +log(Category, Level, Fmt, Args) when is_list(Args) -> + logger:log(Level, Fmt, Args, #{domain => ?DEFINE_RMQLOG_DOMAIN(Category)}). + +debug(Format) -> debug(Format, []). +debug(Format, Args) -> debug(self(), Format, Args). +debug(Pid, Format, Args) -> + ?LOG_DEBUG(Format, Args, #{pid => Pid, + domain => ?RMQLOG_DOMAIN_GLOBAL}). + +info(Format) -> info(Format, []). +info(Format, Args) -> info(self(), Format, Args). +info(Pid, Format, Args) -> + ?LOG_INFO(Format, Args, #{pid => Pid, + domain => ?RMQLOG_DOMAIN_GLOBAL}). + +notice(Format) -> notice(Format, []). +notice(Format, Args) -> notice(self(), Format, Args). +notice(Pid, Format, Args) -> + ?LOG_NOTICE(Format, Args, #{pid => Pid, + domain => ?RMQLOG_DOMAIN_GLOBAL}). + +warning(Format) -> warning(Format, []). +warning(Format, Args) -> warning(self(), Format, Args). +warning(Pid, Format, Args) -> + ?LOG_WARNING(Format, Args, #{pid => Pid, + domain => ?RMQLOG_DOMAIN_GLOBAL}). + +error(Format) -> error(Format, []). +error(Format, Args) -> error(self(), Format, Args). +error(Pid, Format, Args) -> + ?LOG_ERROR(Format, Args, #{pid => Pid, + domain => ?RMQLOG_DOMAIN_GLOBAL}). + +critical(Format) -> critical(Format, []). +critical(Format, Args) -> critical(self(), Format, Args). +critical(Pid, Format, Args) -> + ?LOG_CRITICAL(Format, Args, #{pid => Pid, + domain => ?RMQLOG_DOMAIN_GLOBAL}). + +alert(Format) -> alert(Format, []). +alert(Format, Args) -> alert(self(), Format, Args). +alert(Pid, Format, Args) -> + ?LOG_ALERT(Format, Args, #{pid => Pid, + domain => ?RMQLOG_DOMAIN_GLOBAL}). + +emergency(Format) -> emergency(Format, []). +emergency(Format, Args) -> emergency(self(), Format, Args). +emergency(Pid, Format, Args) -> + ?LOG_EMERGENCY(Format, Args, #{pid => Pid, + domain => ?RMQLOG_DOMAIN_GLOBAL}). + +none(_Format) -> ok. +none(_Format, _Args) -> ok. +none(_Pid, _Format, _Args) -> ok. From 3ee82dab54de3834261e99a2b99d25910b11dcfd Mon Sep 17 00:00:00 2001 From: Michal Kuratczyk Date: Fri, 18 Jul 2025 09:46:00 +0200 Subject: [PATCH 31/31] Updates for SQL filter changes --- deps/rabbit/src/rabbit_amqp_filter_sql.erl | 44 +++++++++++----------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/deps/rabbit/src/rabbit_amqp_filter_sql.erl b/deps/rabbit/src/rabbit_amqp_filter_sql.erl index e1a34ec0073d..2ac7d7f24fdc 100644 --- a/deps/rabbit/src/rabbit_amqp_filter_sql.erl +++ b/deps/rabbit/src/rabbit_amqp_filter_sql.erl @@ -294,33 +294,36 @@ sql_to_list(SQL) -> String when is_list(String) -> {ok, String}; Error -> - ?LOG_WARNING("JMS message selector ~p is not UTF-8 encoded: ~p", - [JmsSelector, Error]), + ?LOG_WARNING("SQL expression ~p is not UTF-8 encoded: ~p", + [SQL, Error]), error end. -check_length(String) - when length(String) > ?MAX_EXPRESSION_LENGTH -> - ?LOG_WARNING("JMS message selector length ~b exceeds maximum length ~b", - [length(String), ?MAX_EXPRESSION_LENGTH]), - error; -check_length(_) -> - ok. +check_length(String) -> + Len = length(String), + case Len =< ?MAX_EXPRESSION_LENGTH of + true -> + ok; + false -> + ?LOG_WARNING("SQL expression length ~b exceeds maximum length ~b", + [Len, ?MAX_EXPRESSION_LENGTH]), + error + end. tokenize(String, SQL) -> case rabbit_amqp_sql_lexer:string(String) of {ok, Tokens, _EndLocation} -> {ok, Tokens}; {error, {_Line, _Mod, ErrDescriptor}, _Location} -> - ?LOG_WARNING("failed to scan JMS message selector '~ts': ~tp", - [JmsSelector, ErrDescriptor]), + ?LOG_WARNING("failed to scan SQL expression '~ts': ~tp", + [SQL, ErrDescriptor]), error end. check_token_count(Tokens, SQL) when length(Tokens) > ?MAX_TOKENS -> - ?LOG_WARNING("JMS message selector '~ts' with ~b tokens exceeds token limit ~b", - [JmsSelector, length(Tokens), ?MAX_TOKENS]), + ?LOG_WARNING("SQL expression '~ts' with ~b tokens exceeds token limit ~b", + [SQL, length(Tokens), ?MAX_TOKENS]), error; check_token_count(_, _) -> ok. @@ -328,8 +331,8 @@ check_token_count(_, _) -> parse(Tokens, SQL) -> case rabbit_amqp_sql_parser:parse(Tokens) of {error, Reason} -> - ?LOG_WARNING("failed to parse JMS message selector '~ts': ~p", - [JmsSelector, Reason]), + ?LOG_WARNING("failed to parse SQL expression '~ts': ~p", + [SQL, Reason]), error; Ok -> Ok @@ -343,15 +346,10 @@ transform_ast(Ast0, SQL) -> end, Ast0) of Ast -> {ok, Ast} - catch {unsupported_field, Name} -> - ?LOG_WARNING( - "identifier ~ts in JMS message selector ~tp is unsupported", - [Name, JmsSelector]), - error; - {invalid_pattern, Reason} -> + catch {invalid_pattern, Reason} -> ?LOG_WARNING( - "failed to parse LIKE pattern for JMS message selector ~tp: ~tp", - [JmsSelector, Reason]), + "failed to parse LIKE pattern for SQL expression ~tp: ~tp", + [SQL, Reason]), error end.