When I try to send a local mail I do not get anything and yet I have no mistake. Normally I should receive the mail on Mailhog. I tested by sending an email with phpmailer and it works perfectly.
Can you help me please
IndexController file
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Mailer\MailerInterface;
class IndexController extends AbstractController
{
/**
* #Route("/", name="index")
*/
public function index(MailerInterface $mailer): Response
{
$email = (new Email())
->from('no-reply#example.com')
->to('user#example.com')
->subject('I love Me')
->html('<h1>Lorem ipsum</h1> <p>...</p>');
try {
$mailer->send($email);
} catch (TransportExceptionInterface $e) {
dump($e);
}
}
}
.env file
###> symfony/webapp-meta ###
MESSENGER_TRANSPORT_DSN=doctrine://default?auto_setup=0
###< symfony/webapp-meta ###
###> symfony/mailer ###
MAILER_DSN=smtp://localhost:1025
###< symfony/mailer ###
mailer.yaml file
framework:
mailer:
dsn: '%env(MAILER_DSN)%'
messenger.yaml file
framework:
messenger:
failure_transport: failed
transports:
# https://symfony.com/doc/current/messenger.html#transport-configuration
async:
dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
options:
use_notify: true
check_delayed_interval: 60000
retry_strategy:
max_retries: 3
multiplier: 2
failed: 'doctrine://default?queue_name=failed'
# sync: 'sync://'
routing:
Symfony\Component\Mailer\Messenger\SendEmailMessage: async
Symfony\Component\Notifier\Message\ChatMessage: async
Symfony\Component\Notifier\Message\SmsMessage: async
# Route your messages to the transports
# 'App\Message\YourMessage': async
Related
I'm using Guzzle as a http client in a Symfony app. With the following code I'm able to log all requests and responses. Is there a way to log also response time?
I tried on_stats but it should be added to each client call and it is not an option.
services:
app.client.default:
class: 'GuzzleHttp\Client'
lazy: true
arguments:
- handler: '#app.handler_stack.default'
app.handler_stack.default:
class: 'GuzzleHttp\HandlerStack'
factory: [ GuzzleHttp\HandlerStack, create ]
calls:
- [ push, [ '#app.middleware.log_default', 'log_default' ] ]
app.middleware.log_default:
class: callback
factory: [ GuzzleHttp\Middleware, log ]
arguments:
- '#logger'
- '#app.log_formatter.default'
app.log_formatter.default:
class: 'GuzzleHttp\MessageFormatter'
arguments:
- ">>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}"
app.service:
class: 'App\Service'
arguments:
- '#app.client.default'
use GuzzleHttp\Client;
class Service {
private $httpClient;
public function __construct(Client $httpClient) {
$this->httpClient = $httpClient;
}
public function apiRequest() {
$response = $this->httpClient->get('https://www.google.com');
// ...
}
}
I try to write logs to a specific file using a specific channel in Monolog (called encuestas_cloud) inside a Command in Symfony 3.4 but I'm not able to do it.
I've read Symfony docs and searched in the web and I think it's well configured but i get an error.
The code is:
In config_dev.yml:
monolog:
handlers:
main:
type: stream
path: '%kernel.logs_dir%/%kernel.environment%.log'
level: debug
channels: ['!event']
...
encuestas_cloud_logger:
#type: rotating_file
type: stream
path: 'D:/web/xampp/htdocs/temp/logs/encuestas_cloud.log'
level: info
channels: ['encuestas_cloud']
max_files: 10
In services.yml
services:
_defaults:
autowire: true
autoconfigure: true
public: false
AppBundle\Command\EncuestasCloudCommand\:
resource: '../../src/AppBundle/Command/EncuestasCloudCommand.php'
arguments: ['#logger']
public: true
tags:
- { name: monolog.logger, channel: encuestas_cloud }
The command:
// src/AppBundle/Command/EncuestasCloudCommand.php
namespace AppBundle\Command;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
...
class EncuestasCloudCommand extends ContainerAwareCommand
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
parent::__construct();
}
...
protected function execute(InputInterface $input, OutputInterface $output)
{
$logger = $this->logger;
$logger->addInfo('My logger is now ready');
When I execute it I get:
In LoggerChannelPass.php line 98:
Monolog configuration error: The logging channel "encuestas_cloud" assigned to the
"encuestas_cloud_logger" handler does not exist.
In ContainerBuilder.php line 1063:
You have requested a non-existent service "monolog.logger.encuestas_cloud".
If I add channels: ['encuestas_cloud'] in config_dev.yml
monolog:
channels: ['encuestas_cloud']
handlers:
main:
type: stream
...
The error dissappear but the log still goes to the general log file: dev.log
Please, could somebody help me to find out what is wrong with the configuration?
Thanks a lot!!!
Does changing the argument for your Command from #logger to #monolog.logger.encuestas_cloud work? That should inject the specific configured logger and therefor your logging would appear in the correct logger.
monolog:
channels: ['encuestas_cloud']
Should be defined AFAIK, and explicitly excluding the channel for your main logger, to not appear there:
monolog:
handlers:
main:
...
channels: [ '!encuestas_cloud' ]
Thanks a lot evertjes for your answer, it didn't solve the problem but helped me to investigate other paths...
The problem was that the command wasn't defined as a service in the right way, so Symfony was unable to match the channel to the service (and to the command).
I executed :
php bin/console debug:container
and the service of the command didn't appear.
So after investigating how to define a command as a service the configuration worked fine... uffff.
Here I post the final code that works.
In config_dev.yml:
monolog:
channels: ['encuestas_cloud']
handlers:
main:
type: stream
path: '%kernel.logs_dir%/%kernel.environment%.log'
level: debug
channels: ['!event','!encuestas_cloud']
...
encuestas_cloud_logger:
type: rotating_file
path: 'D:/web/xampp/htdocs/temp/logs/encuestas_cloud.log'
level: info
channels: ['encuestas_cloud']
max_files: 10
In services.yml
services:
_defaults:
autowire: true
autoconfigure: true
public: false
console.command.encuestas_cloud_command:
class: 'AppBundle\Command\EncuestasCloudCommand'
arguments: ['#logger']
public: true
tags:
- { name: monolog.logger, channel: encuestas_cloud }
The command:
// src/AppBundle/Command/EncuestasCloudCommand.php
namespace AppBundle\Command;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
...
class EncuestasCloudCommand extends ContainerAwareCommand
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
parent::__construct();
}
...
protected function execute(InputInterface $input, OutputInterface $output)
{
$logger = $this->logger;
$logger->addInfo('My logger is now ready');
Now the file is created and the log appears with the configured channel.
Thanks a lot to everybody!!!
I have been using the Group annotation for years on SF2 and SF3.
I'm trying SF4.1. And I'm getting an empty JSON when I send a GET to my endpoint.
The interesting parts of my composer.json:
"friendsofsymfony/rest-bundle": "^2.3",
"jms/serializer-bundle": "^2.3",
"sensio/framework-extra-bundle": "^5.1",
"symfony/serializer-pack": "^1.0"
The config:
framework:
serializer:
enabled: true
enable_annotations: true
sensio_framework_extra:
view: { annotations: true }
fos_rest:
routing_loader:
default_format: json
view:
view_response_listener: 'force'
format_listener:
rules:
- { path: ^/, prefer_extension: true, fallback_format: json, priorities: [ json,xml, html ] }
The Entity
use JMS\Serializer\Annotation\Groups;
class User implements UserInterface, \Serializable
{
private $id;
/**
* #Groups({"api"})
*/
private $username;
And the endpoint API Controller:
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\View\View;
class UserController extends FOSRestController {
public function getUserAction(Request $request, EntityManagerInterface $em)
{
$user = $em->getReference('App:User', 1);
$view = View::create();
$context = new Context();
$context->setGroups(['api']);
$view->setContext($context);
$view->setData($user);
return $this->handleView($view);
}
}
If I remove `$context->setGroups(['api']), the JSON has all the User attributes.
Any idea? Thanks!
Debug Info:
bin/console debug:container jms
Select one of the following services to display its information [fos_rest.serializer.jms]:
[0] fos_rest.serializer.jms
0
Information for Service "fos_rest.serializer.jms"
=================================================
Option Value
Service ID fos_rest.serializer.jms
Class FOS\RestBundle\Serializer\JMSSerializerAdapter
Tags -
Public no
Synthetic no
Lazy yes
Shared yes
Abstract no
Autowired no
Autoconfigured no
By default FOSRest prefers the JMSSerializer if it is installed. So first check if the service defined by the JMSSerializerBundle is defined:
./bin/console debug:container jms_serializer.serializer
If this command displays an error message (ServiceNotFound) then the bundle is not correctly installed. Check the config/bundles.php and add the following line if it's missing:
JMS\SerializerBundle\JMSSerializerBundle::class => ['all' => true],
If it actually is installed, you can check the fos_rest configuration, if it maybe changes the serializer service. You can configure it like that:
fos_rest:
service:
serializer: "fos_rest.serializer.jms"
Config.yml
gos_web_socket:
topics:
- #app.real_time.subscribe
- #app.real_time.push
server:
port: 8000 #The port the socket server will listen on
host: localhost #The host ip to bind to
router:
resources:
- #AppBundle/Resources/config/pubsub/routing.yml
client:
firewall: main #can be an array of firewalls
session_handler: #session.handler.pdo
pushers:
zmq:
default: true
host: 127.0.0.1
port: 8888
persistent: true
protocol: tcp
pubsub/routing.yml
real_time_push:
channel: all/user
handler:
callback: 'app.real_time.push' #related to the getName() of your topic
services.yml
app.real_time.subscribe:
class: AppBundle\RealTime\Subscribe
arguments: [ #gos_web_socket.websocket.client_manipulator ]
app.real_time.push:
class: AppBundle\RealTime\Push
arguments: [ #gos_web_socket.websocket.client_manipulator ]
The following function is getting hit when client subscribes on this topic. I can see the text in the console.
Subscribe Class onSubscribe() : Subscribe.php
public function onSubscribe(ConnectionInterface $connection, Topic $topic, WampRequest $request)
{
var_dump("This user is subscribed");
}
But when pushed via zmq from controller the onPush() function never got hit. I have already implemented TopicInterdace and PushableTopicInterface in Push.php.
Push Class onPush() : Push.php
public function onPush(Topic $topic, WampRequest $request, $data, $provider)
{
var_dump("Helloooooooooooooooooo0000000000");
}
Please can any one tell me where did I do wrong. Thanks in advance. Here is the controller
$pusher = $this->container->get('gos_web_socket.zmq.pusher');
//push(data, route_name, route_arguments)
$pusher->push(['my_data' => 'data'], 'real_time_push', ['username' => 'sujit']);
I am working on a Symfony 2 web app and I would like to inject a Monolog logger using a specific channel to a service:
The Config:
monolog:
handlers:
main:
type: stream
path: %kernel.root_dir%/%kernel.environment%.log
level: error
#channels: [!alert]
alert:
type: stream
path: %kernel.root_dir%/%kernel.environment%.alert.log
level: info
channels: [alert]
Service Config:
services:
some_service:
class: Some\Service
arguments: [#logger]
tags:
- { name: monolog.logger, channel: alert }
The Service:
class SomeService {
protected $logger;
public function __construct($logger) {
$this->logger = $logger;
$this->logger->info('Log this!');
}
The prod.log file:
[2016-03-28 11:25:47] alert.INFO: Log this!
The Problem: Although I specifically inject the logger using the alert channel, the message is handled by the main handler. Thus the messages are logged into the prod.log file instead of the prod.alert.log file.
When I leave the line channels: [!alert] as comment, the message is logged to prod.log. When I activate this line by removing the comment, the message is not logged at all (main handler ignores the channel correctly).
What have I to to, in order to use a specific handler to target a specific log file, mailer, etc? Messages to alert channel should be handled by the alert handler while all other handlers are ignored.
Use special service created for Monolog handler:
services:
some_service:
class: Namespace\Some\Service
arguments: ["#monolog.logger.alert"]