Current section

Files

Jump to
diint_utilites_common_app src log rabbitMQ_logger_handler.erl
Raw

src/log/rabbitMQ_logger_handler.erl

-module(rabbitMQ_logger_handler).
-include("_build/default/lib/amqp_client/include/amqp_client.hrl").
-include("include/types_rabbit.hrl").
-export([adding_handler/1, removing_handler/1, log/2]).
-export([init/1, handle_call/3, handle_cast/2, terminate/2]).
adding_handler(Config) ->
MyConfig = maps:get(config,Config),
{ok, Pid} = gen_server:start(?MODULE, MyConfig, []),
{ok, Config#{config => MyConfig#{pid => Pid}}}.
removing_handler(#{config := #{pid := Pid}}) ->
gen_server:stop(Pid).
log(LogEvent,#{config := #{pid := Pid}} = Config) ->
gen_server:cast(Pid, {log, LogEvent, Config}).
init(#{rabbitConfig := RabbitConfig, exchange := ExchangeName, queueName := QueueName}) ->
RmqConnectionConfig = rabbit_utilites:convert_array_to_rabbit_connection_config(RabbitConfig),
case connect_to_rabbit(RmqConnectionConfig) of
{ok, Connection, Channel} -> {ok, #{connection => Connection, channel => Channel, exchange => ExchangeName, queueName => QueueName}};
_ -> {error, "NoConnect to Log Rabbit"}
end.
handle_call(_, _, State) ->
{reply, {error, bad_request}, State}.
handle_cast({log, LogEvent, Config}, #{connection := _, channel := _, exchange := _, queueName := _} = State) ->
do_log(State, LogEvent, Config),
{noreply, State}.
terminate(_Reason, #{fd := Fd}) ->
_ = file:close(Fd),
ok.
do_log(#{connection := Connection, channel := Channel, exchange := ExchangeName, queueName := QueueName}, LogEvent, #{formatter := {FModule, FConfig}}) ->
String = FModule:format(LogEvent, FConfig),
Props = #'P_basic'{},
amqp_channel:cast(Channel, #'basic.publish'{exchange = ExchangeName}, #amqp_msg{payload = String, props = Props}).
%% так надо, потом уберу
connect_to_rabbit(RabbitConfig) ->
case connect(RabbitConfig) of
{ok, Connection, NewChannel} -> {ok, Connection, NewChannel};
% #'exchange.declare_ok'{} = amqp_channel:call(NewChannel, #'exchange.declare'{exchange = Exchange}),
% #'queue.declare_ok'{} = amqp_channel:call(NewChannel, #'queue.declare'{queue = Queue, auto_delete = false, arguments = RabbitConfig#rabbit_connection_config.arguments}),
% #'queue.bind_ok'{} = amqp_channel:call(NewChannel, #'queue.bind'{queue = Queue, exchange = Exchange}),
Other -> Other
end.
connect(#rabbit_connection_config{ host = Host, username = Username, password = Password, virtual_host=VirtHost}) ->
case amqp_connection:start(#amqp_params_network{host = Host, password = Password, username = Username, heartbeat = 10, frame_max = 8388608, virtual_host = VirtHost}) of
{ok, Connection} ->
case amqp_connection:open_channel(Connection) of
{ok, Channel} ->
{ok, Connection, Channel};
ErrorChannel ->
{error, ErrorChannel}
end;
ErrorConnection ->
{error, ErrorConnection}
end.