Code Monkey home page Code Monkey logo

horse-logger's Introduction

horse-logger

horse-logger is a official middleware to register log in APIs developed with the Horse framework.
We created a channel on Telegram for questions and support:

⚙️ Installation

Installation is done using the boss install command:

boss install horse-logger

If you choose to install manually, simply add the following folders to your project, in Project > Options > Resource Compiler > Directories and Conditionals > Include file search path

../horse-logger/src

✔️ Compatibility

This middleware is compatible with projects developed in:

  • Delphi
  • Lazarus

🧬 Official Providers

Provider Delphi Lazarus
console    ✔️     ✔️
file    ✔️     ✔️

⚡️ Quickstart

Examples are provided within each provider.

⚠️ License

horse-logger is free and open-source middleware licensed under the MIT License.

horse-logger's People

Contributors

andre-djsystem avatar carloshe avatar ramyres110 avatar viniciussanchez avatar vitao-jose avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

horse-logger's Issues

request_content not implemented

request_content not implemented
I add the line:

LLog.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('request_content', THorseLoggerManager.ValidateValue(AReq.RawWebRequest.Content));

in unit Horse.Logger.Manager

Exception ao receber Request com Binary no Body

Ao receber uma request onde no body tem um binário o middleware gera uma exception
exception class EEncodingError with message "No mapping for the Unicode character exists in the target multi-byte code page"

Exemplo de código:

No Header da request definir Content-Type como application/octet-stream

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
Horse,
Horse.OctetStream,
Horse.Logger,
Horse.Logger.Provider.Console,
Horse.Logger.Provider.LogFile,
System.SysUtils,
System.Classes;

var
LLogConsole: THorseLoggerConsoleConfig;
LLogFile: THorseLoggerLogFileConfig;

begin
LLogConsole := THorseLoggerConsoleConfig.New.SetLogFormat('${request_clientip} [${time}] ${response_status}');
THorseLoggerManager.RegisterProvider(THorseLoggerProviderConsole.New());

LLogFile := THorseLoggerLogFileConfig.New
.SetLogFormat('${request_clientip} [${time}] ${response_status}');
THorseLoggerManager.RegisterProvider(THorseLoggerProviderLogFile.New());

THorse.Use(OctetStream);
THorse.Use(THorseLoggerManager.HorseCallback);

THorse.Get('/stream',
procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc)
var
LStream: TFileStream;
begin
LStream := TFileStream.Create(ExtractFilePath(ParamStr(0)) + 'horse.pdf', fmOpenRead);
Res.Send(LStream);
end);

THorse.Post('/stream',
procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc)
var
LStream: TMemoryStream;
begin
LStream := Req.Body;
LStream.SaveToFile(ExtractFilePath(ParamStr(0)) + 'horse.pdf');
Res.Status(THTTPStatus.Created);
end);

THorse.Listen(9000,
procedure(Horse: THorse)
begin
Writeln(Format('Server is runing on %s:%d', [Horse.Host, Horse.Port]));
Readln;
end);
end.

Faltando Unit

Não consegui encontrar essa unit: Horse.Logger.Provider.LogFile

Erro no Horse.Logger.Manager.pas(93) There is no overloaded version of 'ValidateValue' that can be called with these arguments

image

Error:

[dcc32 Error] Horse.Logger.Manager.pas(93): E2250 There is no overloaded version of 'ValidateValue' that can be called with these arguments

Problema causado no commit ad8d600

Há a necessidade de adicionar mais uma condicional de definição (IFDEF) para aceitar o separador!

Correção local:

LLog.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('request_content', THorseLoggerManager.ValidateValue({$IF DEFINED(FPC)} TEncoding.ANSI.GetBytes({$ENDIF}AReq.RawWebRequest.{$IF DEFINED(FPC)}Content){$ELSE}RawContent{$ENDIF}{$IF DEFINED(FPC)},''{$ENDIF}));

Delphi
Embarcadero® RAD Studio 10 Seattle Version 23.0.22248.579

Problem using the Logger

Problem using the Logger

Hello, I'm using the logger but the first request it completes, after the end it hangs with the error

<title>Error 500: Internal Server Error</title>

5🔥🙀

🐎 Internal Server Error 🐎

Access violation at address 00000000 in module 'ExemploHorseAPI.exe'. Read of address 00000000

/pingGetByIdRestFull/1/2/teste/3

Support for log IP behind reverse proxy

Hi, in the cases where Horse is running behind a reverse proxy like Apache, the default log returns the internal proxy's IP instead of the real client IP

Reading about, this info is returned as "x-forwarded-for" header info, but you must be aware of some possible faking in this info

Some sources:
https://serverfault.com/questions/846695/preserve-client-ip-through-apache-reverse-proxy
https://stackoverflow.com/questions/760283/apache-proxypass-how-to-preserve-original-ip-address
https://en.wikipedia.org/wiki/X-Forwarded-For

What better alternative do you suggest?
Thanks!

Memory Leak

Bom dia, atualizei para a versão 2.0.1 e estou recebendo este memory leak abaixo,
image

Após executar alguma requisição ele aparece assim os memory leaks

image

Estou utilizando o provider.LogFile

uses
Horse.Logger,
Horse.Logger.Provider.LogFile;


var
LLogFileConfig: THorseLoggerLogFileConfig;


LLogFileConfig := THorseLoggerLogFileConfig.New
.SetDir(LPath);

THorseLoggerManager.RegisterProvider(
THorseLoggerProviderLogFile.New(LLogFileConfig)
);

THorse.Use(THorseLoggerManager.HorseCallback());

Horse.Logger está travando o recycle do pool no IIS (Aplicação ISAPI x64)

Possuo algumas aplicações no ambiente ISAPI e funcionam normalmente, porém ao tentar dar recycle do pool da aplicação, o pool só é reciclado quando o timeout de "Desligamento" é atingido, durante testes internos notei que o problema estava no Horse.Logger.

Aparentemente a aplicação não está limpando as threads, fiz diversas tentativas diretamente no Horse.Provider.ISAPI, porém não obtive sucesso, deixarei abaixo uma das tentativas que tentei usar para limpar as threads

procedure DoOnTerminate;
begin
  // Terminate threads...
  try
    Log('Log Manager Thread is starting terminate proccess...');

    if THorseLoggerManager.DefaultManager <> nil then
    begin
      THorseLoggerManager.DefaultManager.Terminate;
      THorseLoggerManager.DefaultManager.GetEvent.SetEvent;
      THorseLoggerManager.DefaultManager.WaitFor;
      THorseLoggerManager.DefaultManager.Free;
    end;

    if THorseLoggerManager.DefaultManager <> nil then
      TerminateThread(THorseLoggerManager.DefaultManager.Handle, 0);

    Log('Log Manager Thread is terminated');
  except on E: Exception do
    Log('Log Manager Thread dispath an error: ' + E.StackTrace + #13#10 + E.Message);
  end;
end;

// ...

class procedure THorseProvider<T>.InternalListen;
begin
  CoInitFlags := COINIT_MULTITHREADED;
  Application.Initialize;
  Application.WebModuleClass := WebModuleClass;
  (Application as TISAPIApplication).OnTerminate := DoOnTerminate;
  DoOnListen;
  Application.Run;
end;

O log interno acima, acusa que ele está limpando a thread manager, porém a aplicação não termina o recycle mesmo assim.

Fiz algumas pesquisas relacionadas a ThreadPool no IIS e vi que é uma boa prática finalizar as therads no método TISAPIApplication.OnTerminate ou no método de export TerminateExtension.

Dependências usadas (apenas as relacionadas a issue)

"github.com/hashload/horse": "^3.0.1",
"github.com/hashload/horse-logger": "^2.0.6",

O provider para o logger é interno, foi criado baseado no provider horse-logger-provider-logfile e horse-logger-provider-console

Links relacionados

Imprimentar loggers

Olá

Já tentei seguir seu exemplo mas até agora não foi.

parece que foi atualizado versão e não esta funcinando mais da forma como deveria

aguardo retorno

É possivel pega a linha string gerada pelo Log ?

Olá,

Hoje o Log é criado em um arquivo que vai sendo alimentado requisição por requisição.
Porém eu gostaria de pegar a linha deste log e ao invés de gravar num arquivo, irei gravar numa tabela no meu banco de dados.
é possivel fazer isso?

Grato
Alexandre

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.